In this post, we write a python program to count characters of a string with proper explanation.
We are writing this python program in four different ways:
- Simple way (by taking user input)
- Using function
- Using a python dictionary
- Using python dictionary comprehension
So let’s write a program to count characters of the string in all 4 ways one by one.
A simple way (by taking user input)
This program may ask like:
Write a python program to count characters of string by taking user input.
But before writing this program you should know about:
- How to take user input in python
- If-else
- for loop
- .count() method (count is built-in function in python)
Source code
My_string = input('ENter your string: ')
check_empty = ''
for i in My_string:
if i not in check_empty: # this help you to count unique characters of the string
check_empty += i
string_count = My_string.count(i) # count a character
print(f'{i}: {string_count}')
Output
ENter your string: Ssaurabh
S: 1
s: 1
a: 2
u: 1
r: 1
b: 1
h: 1
Using function
This program may ask like:
Write a python program to count characters of string by using a user-defined function.
But before writing this program you should know about:
- how to take user input
- If-else
- for loop
- .count() method
- Python function
Source code
def count_string(my_string): #define a function
check_present = ''
for character in my_string:
if character not in check_present: #avoid to count a character more than once
check_present+=character
character_count = my_string.count(character) #count a character
print(f'{character}: {character_count}')
my_input = input('ENter your string: ')
count_string(my_input)
Output
ENter your string: hiiiiiiinaaaaaa
h: 1
i: 7
n: 1
a: 6
Using python Dictionary
This program may ask like:
Write a python program to count characters of strings using Dictionary.
But before writing this program you should know about:
- how to take user input
- for loop
- .count() method
- python Dictionary
Source code
word = input('ENter your word for count: ')
d = {} #empty dictionary
for i in word:
d[i] = word.count(i) #count and add to dictionary
print(d)
Output
ENter your word for count: roose
{'r': 1, 'o': 2, 's': 1, 'e': 1}
Using python dictionary comprehension
this program may ask like:
Count characters of string using dictionary comprehension in python.
But before writing this program you should know about Dictionary comprehension.
Source code
my_string = input('ENter your world: ')
counting = {i : my_string.count(i) for i in my_string}
print(counting)
Output
ENter your world: jennifer
{'j': 1, 'e': 2, 'n': 2, 'i': 1, 'f': 1, 'r': 1}
Hope this post adds some value to your life – thank you.