【问题标题】:How to count a specif letter in word. - Python如何计算单词中的特定字母。 - Python
【发布时间】:2021-12-12 01:16:47
【问题描述】:

Python

我编写了一个程序,它读取用户的字符串输入,然后要求删除一个字符,然后打印输入字符串而不包含用户选择的字符。之后,我希望用户输入单词的一个字符,然后代码将计算单词中有多少所选字符。我正在努力打印正确的答案。

例如。输入=香蕉|字符 = 0 |打印 = 凤梨 |计数字符 = 一个 |计数 = 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

【问题讨论】:

    标签: python string for-loop if-statement count


    【解决方案1】:

    for 循环中的 i 与您从用户那里收到的输入不同。相反,你应该写:

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

    【讨论】:

    • 谢谢,伙计,感谢您的帮助!
    【解决方案2】:

    在递增计数器之前,您需要满足一个条件。此外,您正在循环中覆盖变量 i

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

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2020-10-04
      • 2011-06-01
      • 1970-01-01
      • 2011-09-15
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多