【问题标题】:can we make a for each in python我们可以在 python 中为每个创建一个吗
【发布时间】:2020-06-24 16:39:14
【问题描述】:

我想制作一个程序来计算文本中的字母 A

f = open('text.txt', 'r')
content = f.read()
i = 1
for each a in content:
     i = i + 1``
     print(i)

【问题讨论】:

  • Python 只有一个“foreach”循环。这就是for 的含义。如果要检查某个字符,则需要手动执行。

标签: python python-3.x for-loop text


【解决方案1】:

执行此特定任务的最佳方法是使用内置的count() 函数。那么代码就变成了:

f = open('text.txt', 'r')
content = f.read()
print(content.count("A"))

【讨论】:

    【解决方案2】:

    我想这就是你想要的:

    with open('text.txt', 'r') as f:
        i = 0
        for char in f:
            if char == 'a':
                i += 1
    
    print(f'There are {i} a\'s in the txt file.')
    

    【讨论】:

      【解决方案3】:
      string.count(substring)
      content.count("a")
      

      【讨论】:

      • 如果您解释了您提供的代码如何回答问题,这将是一个更好的答案。
      猜你喜欢
      • 2021-06-07
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2015-03-12
      • 2021-12-10
      • 1970-01-01
      • 1970-01-01
      • 2019-09-27
      相关资源
      最近更新 更多