Python - Ignore Letter Case
Solution 1:
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()) isFalse
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()
Solution 2:
Use the following:
if rules.lower() == rulesa.lower():
This converts both strings to lower case before testing for equality.
Solution 3:
A common approach is to make the input upper or lower case, and compare with an upper or lower case word:
rulesa = 'yes'if rules.lower() == rulesa:
# do stuff
Solution 4:
You can make either of uppercase comparison or lowercase comparison.
For Example:
rulesa.upper() == rules.upper()
or
rulesa.lower() == rules.lower()
both will give you output as true
Solution 5:
rules = raw_input("Would you like to read the instructions? ")
rulesa = "Yes"if (rules == rulesa) or (rules.lower() == rulesa.lower()) or rules.upper() == rulesa.uppper():
print ("No cheating")
else: print ("Have fun!")
That will work everytime no matter the input and will keep the user's input as it was inputed! Have fun with it.
Post a Comment for "Python - Ignore Letter Case"