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

Question:

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

Asked By: lsbc828

||

Answers:

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

Answered By: Chelsea

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")
Answered By: Hetal Thaker

Try pasting this:

word = "hello My name is Bob"

for i in word.upper():
   if i == "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.

Answered By: SenaThenu
Categories: questions Tags:
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.