简体   繁体   中英

How to count a specif letter in word. - Python

Python

I made a program that reads the user's string input, then asks for a character to be removed, and then prints the input string without the character the user chose. After that, I want the user to enter a character of the word and then the code will count how many of the chosen character are in the word. I'm struggling to print the correct answer.

ex. input = banana | character = 0 | print = anana | count character = a | count = 3

s = input ('Enter a string: ')

if s == '': 
    print ('Empty String, please enter a string: ')
else:
    d = int(input('Please enter the character to be removed: '))

    print('The new string is: ', s[:d] + s[d+1:])

i = input ('Enter a character: ')
count = 0

for i in s:
        count = count + 1
print (count)
Output

Enter a string: banana
Please enter the character to be removed: 0
The new string is: anana
Enter a character: a
6

You need to have a condition to be met before incrementing the counter. Also you're overwriting the variable i in your loop:

for c in s:
    if c == i:
        count += 1

The i in your for loop is not the same as the input you received from user. Instead, you should write:

l = input ('Enter a character: ')
count = 0
for i in s:
    if l == i:
        count += 1

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM