不区分大小写的用户输入字符串
Case insensitive user input strings
使用哪个函数使用户输入的字符串不区分大小写?
correctAnswer = "London"
userGuess = input("What is the capital of Great Britain?: ")
if userGuess == "London":
print("Correct!")
else:
print("Wrong")
我试过字符串后面的函数:
.lower()
.capitalize()
.casefold()
输出仍然是 'wrong',尽管当输入是
时答案应该是正确的
- 伦敦
-lOndoN
- 伦敦
等等..
在你的字符串比较中,正确答案本身的第一个字母大写。
correctAnswer = "london"
userGuess = input("What is the capital of Great Britain?: ").lower()
if userGuess == correctAnswer:
print("Correct!")
else:
print("Wrong")
我认为你的问题是 correctAnswer
不是小写,而是 titled。 Python 不区分大小写,但您可以将相同的函数应用于正确答案和 userGuess 以比较它们。
您的选择是:
- 将
.lower()
应用到correctAnswer
- 将
correctAnswer
更改为correctAnswer = "london"
并使用userGuess.lower()
- 使用
userGuess.title()
和correctAnswer = "London"
当比较case-insensitive个字符串时,通常的做法是全部用小写进行比较。
事实上,在您的程序中,没有必要将输入与 London
(大写 "l")进行比较,这就是您应该与 london
进行比较的原因。
比较方式如下:
correct_answer = "london"
userGuess = input("What is the capital of Great Britain?: ")
if userGuess.lower() == correct_answer:
print("Correct!")
else:
print("Wrong")
注意
我在 if 语句中使用了 lower()
方法,而不是在输入语句中。这样更好,因此您可以按原样保留用户的输入,也许您以后会以其他方式使用它。
你可以试试这个:
correctAnswer = "London"
userGuess = input("What is the capital of Great Britain?: ")
userGuess = userGuess.capitalize()
#print(userGuess)
if userGuess == correctAnswer:
print("Correct!")
else:
print("Wrong")
capitalize() 方法将字符串的第一个字符转换为大写(大写)字母。
使用哪个函数使用户输入的字符串不区分大小写?
correctAnswer = "London"
userGuess = input("What is the capital of Great Britain?: ")
if userGuess == "London":
print("Correct!")
else:
print("Wrong")
我试过字符串后面的函数:
.lower()
.capitalize()
.casefold()
输出仍然是 'wrong',尽管当输入是
时答案应该是正确的
- 伦敦
-lOndoN
- 伦敦
等等..
在你的字符串比较中,正确答案本身的第一个字母大写。
correctAnswer = "london"
userGuess = input("What is the capital of Great Britain?: ").lower()
if userGuess == correctAnswer:
print("Correct!")
else:
print("Wrong")
我认为你的问题是 correctAnswer
不是小写,而是 titled。 Python 不区分大小写,但您可以将相同的函数应用于正确答案和 userGuess 以比较它们。
您的选择是:
- 将
.lower()
应用到correctAnswer
- 将
correctAnswer
更改为correctAnswer = "london"
并使用userGuess.lower()
- 使用
userGuess.title()
和correctAnswer = "London"
当比较case-insensitive个字符串时,通常的做法是全部用小写进行比较。
事实上,在您的程序中,没有必要将输入与 London
(大写 "l")进行比较,这就是您应该与 london
进行比较的原因。
比较方式如下:
correct_answer = "london"
userGuess = input("What is the capital of Great Britain?: ")
if userGuess.lower() == correct_answer:
print("Correct!")
else:
print("Wrong")
注意
我在 if 语句中使用了 lower()
方法,而不是在输入语句中。这样更好,因此您可以按原样保留用户的输入,也许您以后会以其他方式使用它。
你可以试试这个:
correctAnswer = "London"
userGuess = input("What is the capital of Great Britain?: ")
userGuess = userGuess.capitalize()
#print(userGuess)
if userGuess == correctAnswer:
print("Correct!")
else:
print("Wrong")
capitalize() 方法将字符串的第一个字符转换为大写(大写)字母。