Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Python - Ignore letter case

Tags:

python

I have an if statement:

rules = input ("Would you like to read the instructions? ")
rulesa = "Yes"
if rules == rulesa:
    print  ("No cheating")
else: print ("Have fun!")

I wish for the user to be able to answer with Yes, YES, yES, yes or any other capitalisation, and for the code to know that they mean Yes.

like image 842
Jack Anyon Avatar asked Feb 24 '16 10:02

Jack Anyon


1 Answers

For this simple example you can just compare lowercased rules with "yes":

rules = input ("Would you like to read the instructions? ")
rulesa = "yes"
if rules.lower() == rulesa:
    print  ("No cheating")
else: 
    print ("Have fun!")

It is OK for many cases, but be awared, some languages may give you a tricky results. For example, German letter ß gives following:

"ß".lower() is "ß"
"ß".upper() is "SS"
"ß".upper().lower() is "ss"
("ß".upper().lower() == "ß".lower()) is False

So we may have troubles, if our string was uppercased somewhere before our call to lower(). Same behaviour may also be met in Greek language. Read the post https://stackoverflow.com/a/29247821/2433843 for more information.

So in generic case, you may need to use str.casefold() function (since python3.3), which handles tricky cases and is recommended way for case-independent comparation:

rules.casefold() == rulesa.casefold()

instead of just

rules.lower() == rulesa.lower()
like image 164
Nikolai Saiko Avatar answered Sep 21 '22 12:09

Nikolai Saiko