Python program to print occurrence of character in string

0 votes

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, 2019 in Python by digger
• 26,670 points

edited Jan 8, 2019 by Omkar 4,677 views

3 answers to this question.

+1 vote

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, 2019 by Omkar
• 69,040 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, 2019 by Anubhav
• 200 points
thank you too so much .. after searching all the day finally i got it .. thanks again
0 votes
Try below code

string = input("Enter a string: ")
lst1 = []
for char in string:
    if char not in lst1:
        lst1.append(char)
for item in lst1:
    print(item,string.count(item), sep = ",")
answered May 28 by Anubhav
• 200 points

Related Questions In Python

+1 vote
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
4,605 views
+1 vote
1 answer
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
267 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, 2019 in Python by Neha
• 330 points

edited Jul 8, 2019 by Kalgi 1,072 views
0 votes
0 answers
+4 votes
6 answers
+3 votes
2 answers

how to print array integer without [] bracket in python like result = 1,2,3,4,5

Hey @abhijmr.143, you can print array integers ...READ MORE

answered Aug 4, 2018 in Python by Omkar
• 69,040 points

edited Aug 8, 2018 by Omkar 3,640 views