[英]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()
輸入仍然是正確的答案時,輸出仍然是“錯誤的”:
-倫敦
-倫敦
-倫敦
等等..
在字符串比較中,正確答案本身的首字母大寫。
correctAnswer = "london"
userGuess = input("What is the capital of Great Britain?: ").lower()
if userGuess == correctAnswer:
print("Correct!")
else:
print("Wrong")
我認為您的問題是correctAnswer
不是小寫字母,而是標題為 。 Python不會區分大小寫,但是您可以將相同的函數應用於正確的答案,並使用userGuess進行比較。
您的選擇是:
.lower()
來correctAnswer
correctAnswer
以userGuess.lower()
correctAnswer = "london"
並使用userGuess.lower()
userGuess.title()
和correctAnswer = "London"
比較不區分大小寫的字符串時,通常將所有字母與小寫字母進行比較。 實際上,在您的程序中,沒有必要將輸入與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()方法將字符串的第一個字符轉換為大寫(大寫)字母。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.