Python program to print occurrence of character in string

+1 vote

I am trying to write a program which counts and print the numbers of each character in a string input by the console.

Example: If the following string is given as input to the program:

abcdefgabc

Then, the output of the program should be:

a,2

c,2

b,2

e,1

d,1

g,1

f,1

Please provide the code for this

Jan 8 in Python by digger
• 27,640 points

edited Jan 8 by Omkar 540 views

2 answers to this question.

0 votes

Try this:

string=input("Enter the string !!")

newstr=list(string)

newlist=[]

for j in newstr:

    if j not in newlist:

        newlist.append(j)

        count=0

        for i in range(len(newstr)):

            if j==newstr[i]:

                count+=1

        print("{},{}".format(j,count))
answered Jan 8 by Omkar
• 67,460 points
+1 vote

Try the below code

inputString = input("Enter a string: ").casefold()

#casefold() is to ensure that uppercase and lower case charachter is treated same.
#If you don't want, you can remove casefold()

tempStr = ''
for char in inputString:
    if char not in tempStr:
        print(char, ', ', inputString.count(char))
        tempStr = tempStr+char
answered Feb 26 by Anubhav
• 160 points

Related Questions In Python

0 votes
1 answer

How to print first character of each word in upper case of a string in Python

You can use split() using space as ...READ MORE

answered Jun 1, 2018 in Python by george
• 200 points
1,786 views
0 votes
2 answers

Finding the index of a character in python string

You can use word.find('o') as well to ...READ MORE

answered Jun 1, 2018 in Python by george
• 200 points
99 views
0 votes
1 answer

How to get the size of a string in Python?

If you are talking about the length ...READ MORE

answered Jun 4, 2018 in Python by ariaholic
• 7,340 points
87 views
–1 vote
2 answers

How to find the size of a string in Python?

following way to find length of string  x ...READ MORE

answered Mar 29 in Python by rajesh
• 1,210 points
81 views
0 votes
1 answer

How to print objects of class using print function in Python?

It can be done as shown below: class Element: ...READ MORE

answered Dec 3, 2018 in Python by Nymeria
• 3,520 points

edited Dec 19, 2018 by Nymeria 480 views
0 votes
1 answer

How to change one character in a string in Python?

Python strings are immutable, you change them ...READ MORE

answered Dec 4, 2018 in Python by Nymeria
• 3,520 points
61 views
+1 vote
2 answers

how can i count the items in a list?

Syntax :            list. count(value) Code: colors = ['red', 'green', ...READ MORE

answered Jul 6 in Python by Neha
• 330 points

edited Jul 8 by Kalgi 225 views
+4 votes
6 answers