Python - 忽略字母大小写

Jac*_*yon 2 python

我有一个if声明:

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

我希望用户能够回答Yes,YES,yES,yes或任何其他大小写,并且代码知道他们的意思是Yes.

Nik*_*iko 9

对于这个简单的例子,您可以将lowercased rules"yes":

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

在许多情况下都可以,但请注意,某些语言可能会给您带来棘手的结果.例如,德文字母ß给出以下内容:

"ß".lower() is "ß"
"ß".upper() is "SS"
"ß".upper().lower() is "ss"
("ß".upper().lower() == "ß".lower()) is False
Run Code Online (Sandbox Code Playgroud)

所以我们可能会遇到麻烦,如果我们的字符串在我们打电话之前的某个地方被大写了lower().希腊语也可以满足相同的行为.有关更多信息,阅读 /sf/answers/2047347501/.

因此,在通用情况下,您可能需要使用str.casefold()函数(因为python3.3),它处理棘手的案例,并且是用于案例独立比较的推荐方法:

rules.casefold() == rulesa.casefold()
Run Code Online (Sandbox Code Playgroud)

而不仅仅是

rules.lower() == rulesa.lower()
Run Code Online (Sandbox Code Playgroud)