Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Count characters in Python

Write a program whose input is a string which contains a character and a phrase, and whose output indicates the number of times the character appears in the phrase.

Ex: If the input is:

n Monday

the output is:

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

1

Ex: If the input is:

z Today is Monday

the output is:

0

Ex: If the input is:

n It's a sunny day

the output is:

2

Case matters.

Ex: If the input is:

n Nobody

the output is:

0

n is different than N.


Here is my code for this problem:

str1 = str(input())
count1 = 0
for i in range(0, len(str1)):
if str1[0] = str1[i]:
count = 1
count1 = count - 1
print(str1[0] + 'appears' + 'this many times in' + str1[1:] + 'is:' + str(count1))

However, this answer is incorrect. Where did I go wrong?

>Solution :

There are grammatical errors, and I’m not sure why there are two counters(count, count1). However, how about this code snippet?

str1 = input()
count = 0
for i in range(2, len(str1)):
    if str1[0] == str1[i]:
        count = count + 1
# print(str1[0] + 'appears' + 'this many times in' + str1[2:] + 'is:' + str(count))
print(f"{str1[0]} appears this many times in {str1[2:]} is: {count}")
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading