【问题标题】:Why does my python function not return the correct times the letters are in the string?为什么我的 python 函数没有返回字母在字符串中的正确时间?
【发布时间】:2023-02-02 00:51:54
【问题描述】:
word = "hello My name is Bob"
for i in word:
   if i == "m":
      print("There is an M")

为什么不打印两次,有两个“m”

【问题讨论】:

    标签: python


    【解决方案1】:

    你必须做 i.lower() 小写“M”

    【讨论】:

    • 然后降低整个句子,而不是一个字母一个字母地降低。
    【解决方案2】:

    Python 是一种区分大小写的语言,因此“M”和“m”是不同的。因此要通过忽略大小写来比较它们,需要将两边都转换为小写或大写。下面的代码会给你结果要么是“M”要么是“m” 如 :

    word = "hello My name is Bob"
    for i in word:
       if i.lower() == "m".lower():
          print("There is an M")
    

    【讨论】:

    • 小建议:for letter in word.lower():if letter == "m":
    【解决方案3】:

    尝试粘贴这个:

    word = "hello My name is Bob"
    
    for i in word.upper():
       if i == "M":
             print("There is an M")
    

    输出的问题是 Python 的大小写敏感性。 Python 读取您的“word”变量并只找到一个“m”(简单 m)。所以它只打印一次。通过添加 '.lower()',我们将整个字符串转换为导致预期输出的简单字母。?

    【讨论】:

      猜你喜欢
      • 2015-05-09
      • 1970-01-01
      • 2019-06-20
      • 1970-01-01
      • 2014-06-14
      • 2021-03-06
      • 1970-01-01
      • 2022-01-04
      • 1970-01-01
      相关资源
      最近更新 更多