TechBeamersTechBeamers
  • Learn ProgrammingLearn Programming
    • Python Programming
      • Python Basic
      • Python OOP
      • Python Pandas
      • Python PIP
      • Python Advanced
      • Python Selenium
    • Python Examples
    • Selenium Tutorials
      • Selenium with Java
      • Selenium with Python
    • Software Testing Tutorials
    • Java Programming
      • Java Basic
      • Java Flow Control
      • Java OOP
    • C Programming
    • Linux Commands
    • MySQL Commands
    • Agile in Software
    • AngularJS Guides
    • Android Tutorials
  • Interview PrepInterview Prep
    • SQL Interview Questions
    • Testing Interview Q&A
    • Python Interview Q&A
    • Selenium Interview Q&A
    • C Sharp Interview Q&A
    • PHP Interview Questions
    • Java Interview Questions
    • Web Development Q&A
  • Self AssessmentSelf Assessment
    • Python Test
    • Java Online Test
    • Selenium Quiz
    • Testing Quiz
    • HTML CSS Quiz
    • Shell Script Test
    • C/C++ Coding Test
Search
  • Python Multiline String
  • Python Multiline Comment
  • Python Iterate String
  • Python Dictionary
  • Python Lists
  • Python List Contains
  • Page Object Model
  • TestNG Annotations
  • Python Function Quiz
  • Python String Quiz
  • Python OOP Test
  • Java Spring Test
  • Java Collection Quiz
  • JavaScript Skill Test
  • Selenium Skill Test
  • Selenium Python Quiz
  • Shell Scripting Test
  • Latest Python Q&A
  • CSharp Coding Q&A
  • SQL Query Question
  • Top Selenium Q&A
  • Top QA Questions
  • Latest Testing Q&A
  • REST API Questions
  • Linux Interview Q&A
  • Shell Script Questions
© 2024 TechBeamers. All Rights Reserved.
Reading: Compute Frequency in Python String
Font ResizerAa
TechBeamersTechBeamers
Font ResizerAa
  • Python
  • SQL
  • C
  • Java
  • Testing
  • Selenium
  • Agile Concepts Simplified
  • Linux
  • MySQL
  • Python Quizzes
  • Java Quiz
  • Testing Quiz
  • Shell Script Quiz
  • WebDev Interview
  • Python Basic
  • Python Examples
  • Python Advanced
  • Python OOP
  • Python Selenium
  • General Tech
Search
  • Programming Tutorials
    • Python Tutorial
    • Python Examples
    • Java Tutorial
    • C Tutorial
    • MySQL Tutorial
    • Selenium Tutorial
    • Testing Tutorial
  • Top Interview Q&A
    • SQL Interview
    • Web Dev Interview
  • Best Coding Quiz
    • Python Quizzes
    • Java Quiz
    • Testing Quiz
    • ShellScript Quiz
Follow US
© 2024 TechBeamers. All Rights Reserved.
Python ExamplesPython Tutorials

Compute Frequency in Python String

Last updated: Nov 05, 2023 12:09 am
By Meenakshi Agarwal
Share
5 Min Read
Count frequency of each character in a Python string
Count frequency of each character in a Python string
SHARE

This tutorial provides several techniques to compute the frequency of each character in a Python string, followed by simple examples.

Contents
Novice approach – Use A dictionary for the frequency of charsUsing collections.Counter() to print character frequencyDictionary’s get() method to compute char frequencyPython set() method to compute character frequency

Here, we have to write a program that will take an input string and count the occurrence of each character in it. We can solve this problem with different programming logic. Let’s check out each solution one by one.

Python Program – Compute Frequency of Characters in a String

It is always interesting to address a problem by taking different approaches. A real programmer keeps trying and continues thinking of doing things in a better way.

Novice approach – Use A dictionary for the frequency of chars

It is the simplest way to count the character frequency in a Python string. You can take a dictionary, and use its keys to keep the char and the corresponding values for the number of occurrences. It just requires incrementing each value field by 1.

See the full logic in the below coding snippet.

"""
Python Program:
 Using a dictionary to store the char frequency in string
"""
input_string = "Data Science"
frequencies = {} 
  
for char in input_string: 
   if char in frequencies: 
      frequencies[char] += 1
   else: 
      frequencies[char] = 1

# Show Output
print ("Per char frequency in '{}' is :\n {}".format(input_string, str(frequencies)))

The result of the above coding snippet is as follows:

Per char frequency in 'Data Science' is :
 {'D': 1, 'a': 2, 't': 1, ' ': 1, 'S': 1, 'c': 2, 'i': 1, 'e': 2, 'n': 1}

Using collections.Counter() to print character frequency

Subsequently, you can use Python’s collection module to expose the counter() function. It computes the frequency of each character and returns a dictionary-like object.

See the full logic in the below coding snippet.

"""
Python Program:
 Using collections.Counter() to print the char frequency in string
"""
from collections import Counter

input_string = "Data Science"

frequency_per_char = Counter(input_string)

# Show Output
print ("Per char frequency in '{}' is :\n {}".format(input_string, str(frequency_per_char)))
print ("Type of frequency_per_char is: ", type(frequency_per_char))

The result of the above coding snippet is as follows:

Per char frequency in 'Data Science' is :
 Counter({'a': 2, 'c': 2, 'e': 2, 'D': 1, 't': 1, ' ': 1, 'S': 1, 'i': 1, 'n': 1})
Type of frequency_per_char is:  <class 'collections.Counter'>

Dictionary’s get() method to compute char frequency

We’ve seen two approaches so far in this tutorial.  However, we can further fine-tune our previous logic of using a Python dictionary and use its get() function instead. This method allows us to set the key value to zero for a new char or increment by one otherwise.

See the full logic in the below coding snippet.

"""
Python Program:
 Using dict.get() to print the char frequency in string
"""
input_string = "Data Science"

frequency_table = {} 
  
for char in input_string: 
    frequency_table[char] = frequency_table.get(char, 0) + 1

# Show Output
print ("Character frequency table for '{}' is :\n {}".format(input_string, str(frequency_table)))

After executing the above code, you see the following result:

Character frequency table for 'Data Science' is :
 {'D': 1, 'a': 2, 't': 1, ' ': 1, 'S': 1, 'c': 2, 'i': 1, 'e': 2, 'n': 1}

Python set() method to compute character frequency

With the help of Python’s set() method, we can accomplish this assignment. Besides, we’ll need to make use of the count() function to keep track of the occurrence of each character in the string.

See the full logic in the below coding snippet.

"""
Python Program:
 Using dict.get() to print the char frequency in string
"""
input_string = "Data Science"

frequency_table = {char : input_string.count(char) for char in set(input_string)} 

# Show Output
print ("Character frequency table for '{}' is :\n {}".format(input_string, str(frequency_table)))
print ("Type of 'frequency_table' is: ", type(frequency_table))

After executing the above code, you see the following result:

Character frequency table for 'Data Science' is :
 {'D': 1, 'i': 1, 'n': 1, ' ': 1, 't': 1, 'S': 1, 'e': 2, 'c': 2, 'a': 2}
Type of 'frequency_table' is:  <class 'dict'>

Please note that the output of the above approach is also a dictionary object. To learn more, read our flagship Python tutorial for beginners and advanced learners.

You Might Also Like

How to Connect to PostgreSQL in Python

Generate Random IP Address (IPv4/IPv6) in Python

Python Remove Elements from a List

How to Use Extent Report in Python

10 Python Tricky Coding Exercises

Meenakshi Agarwal Avatar
By Meenakshi Agarwal
Follow:
Hi, I'm Meenakshi Agarwal. I have a Bachelor's degree in Computer Science and a Master's degree in Computer Applications. After spending over a decade in large MNCs, I gained extensive experience in programming, coding, software development, testing, and automation. Now, I share my knowledge through tutorials, quizzes, and interview questions on Python, Java, Selenium, SQL, and C# on my blog, TechBeamers.com.
Previous Article Multiple Ways to Iterate Strings in Python Iterate Strings in Python (5 Ways)
Next Article Count frequency of each word in a Python string Compute Frequency of Each Word in Python String

Popular Tutorials

SQL Interview Questions List
50 SQL Practice Questions for Good Results in Interview
SQL Interview Nov 01, 2016
Demo Websites You Need to Practice Selenium
7 Sites to Practice Selenium for Free in 2024
Selenium Tutorial Feb 08, 2016
SQL Exercises with Sample Table and Demo Data
SQL Exercises – Complex Queries
SQL Interview May 10, 2020
Java Coding Questions for Software Testers
15 Java Coding Questions for Testers
Selenium Tutorial Jun 17, 2016
30 Quick Python Programming Questions On List, Tuple & Dictionary
30 Python Programming Questions On List, Tuple, and Dictionary
Python Basic Python Tutorials Oct 07, 2016
//
Our tutorials are written by real people who’ve put in the time to research and test thoroughly. Whether you’re a beginner or a pro, our tutorials will guide you through everything you need to learn a programming language.

Top Coding Tips

  • PYTHON TIPS
  • PANDAS TIPSNew
  • DATA ANALYSIS TIPS
  • SELENIUM TIPS
  • C CODING TIPS
  • GDB DEBUG TIPS
  • SQL TIPS & TRICKS

Top Tutorials

  • PYTHON TUTORIAL FOR BEGINNERS
  • SELENIUM WEBDRIVER TUTORIAL
  • SELENIUM PYTHON TUTORIAL
  • SELENIUM DEMO WEBSITESHot
  • TESTNG TUTORIALS FOR BEGINNERS
  • PYTHON MULTITHREADING TUTORIAL
  • JAVA MULTITHREADING TUTORIAL

Sign Up for Our Newsletter

Subscribe to our newsletter to get our newest articles instantly!

Loading
TechBeamersTechBeamers
Follow US
© 2024 TechBeamers. All Rights Reserved.
  • About
  • Contact
  • Disclaimer
  • Privacy Policy
  • Terms of Use
TechBeamers Newsletter - Subscribe for Latest Updates
Join Us!

Subscribe to our newsletter and never miss the latest tech tutorials, quizzes, and tips.

Loading
Zero spam, Unsubscribe at any time.
x