python - 想要查找特定字符在特定句子中出现的次数

标签 python python-3.x

代码

sentence = input("Please enter a sentence:")
character = input("Please enter a single character:")

counter = 0
  1. 使用while循环:
while len(character) > 1:
      character = input("Please try again, enter a single character:")
  • 我的问题是 if 语句对我不起作用。
  • while len(sentence) > counter:
        if sentence[0].__contains__(character):
            counter += 1
            print(counter)
        if sentence[1].__contains__(character):
            counter += 1
            print(counter)
        if sentence[3].__contains__(character):
            counter += 1
            print(counter)
        if sentence[4].__contains__(character):
            counter += 1
            print(counter)
        if sentence[5].__contains__(character):
            counter += 1
            print(counter)
        if sentence[6].__contains__(character):
            counter += 1
            print(counter)
        if sentence[7].__contains__(character):
            counter += 1
            print(counter)
    

    主要问题是用户输入的句子是否大于或小于代码未采用的“if 语句”数量

    最佳答案

    使用 Counter :

    from collections import Counter
    
    sentence = input("Please enter a sentence:")
    character = input("Please enter a single character:")
    
    letter_cnts = Counter(sentence)
    
    # Using format
    print('Your character {cha} occurs {cnt} times in the sentence'.format(cha=character, cnt=letter_cnts[character]))
    
    # Using f-strings
    print(f'Your character "{character}" occurs {letter_cnts[character]} times in the sentence')
    

    关于python - 想要查找特定字符在特定句子中出现的次数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58917706/

    相关文章:

    macos - Mac OS X 10.6 Snow Leopard 上的 Python 3.1.1

    python - 根据列表的大小创建具有固定前缀的字符串列表

    python - 从 IMDbPy 结果中的片目中获取电影 ID

    python - 如何在Sqlalchemy中加载数量有限的集合?

    python - 在python2.7中将时间戳字符串转换为带或不带时区的Unix时间

    python - 为什么在 Pandas 数据框中使用 Z-score 进行标准化会生成 NaN 列?

    python - 在内联 if/else 语句中分配多个值

    python - 将时间字符串转换为十进制小时数?

    python - 文件新行写入

    python - mkdir 的子文件夹在终端中工作,但不能从 python 中工作