How can I make the same_name function ignore the case of the strings?

Question

In this exercise, the same_name() function will compare the two names to see if they are equal. How can this be done so that it will ignore any differences in capitalization?

Answer

This can be done by converting the strings to all lower-case using lower() OR all upper-case using upper() before performing the equality test. The upper() and lower() methods are called on the string variables. For example, to compare the strings as lower-case, the check can be written as:

if your_name.lower() == my_name.lower():

The same would apply for using upper().

16 Likes

Could this also be done by putting the variable inside the upper/lower brackets? For example:
If lower(your_name) == lower(my_name):

sure, if you have a function named lower.

1 Like

str.lower() is a function built into python. You can use the below code in place of the code provided by ajaxninja66418 and get the same results.
Now I’m not sure if there are any benefits to using one over the other.

if str.lower(your_name) == str.lower(my_name):

Write your same_name function here:

def same_name(your_name, my_name):
if your_name == my_name:
return “His name is my name too.”
else:
return False

Uncomment these function calls to test your same_name function:

#print(same_name(“Colby”, “Colby”))

should print True

#print(same_name(“Tina”, “Amber”))

should print False

print(same_name(“John Jacob Jingleheimerschmidt”, “John Jacob Jingleheimerschmidt”))

You can do this with either the .upper() or .lower() method. Essentially you want to “standardize” the characters so that they are all either lowercase or uppercase. This ensures the function compares the character regardless of case. I used .upper for my code.

def same_name(your_name, my_name):
  #standardize both strings to uppercase so that function compares strings without regard to case deviations.  
  if (your_name.upper() == my_name.upper()):
    return True
  else:
    return False

So if,

if your_name.lower() == my_name.lower()

Is used to convert strings to lower (or upper) case letters.
Are there other ways of converting strings using the “string.xxxx()” method?
Also what are theses called when you use the " . " to change a string?

Thanks