Home > Mobile >  Why does my python function not return the correct times the letters are in the string?
Why does my python function not return the correct times the letters are in the string?

Time:02-17

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

Why is it not printing two times, there r two "m"s

CodePudding user response:

You have to do i.lower() to lowercase the "M"

CodePudding user response:

Python is a case-sensitive language so "M" and "m" are different. so to compare them by ignoring the case it requires conversion of both the side either lower or upper case. Below code will give you result either it's "M" or "m" such as :

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

CodePudding user response:

Try pasting this:

word = "hello My name is Bob"

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

The issue with your output is Python's case sensitivity. Python reads your 'word' variable and finds only one 'm'(simple m). So it prints only one time. By adding '.lower()', we convert the whole string into simple letters leading to the expected output.

  • Related