如何使此代码不区分大小写?

2024-04-29 02:44:50 发布

您现在位置:Python中文网/ 问答频道 /正文

我是编程新手,所以我正在尝试一些东西,看看我是否真正理解。我能够使这个“程序”不区分大小写,但非常糟糕(因为我必须为同一个答案设置3个变量,只是为了使它不区分大小写)。我怎样才能使这个代码更好?你知道吗

fav_color = "Red"
fav_color2 = "RED"
fav_color3 = "red"
guess_count = 0
guess_limit = 3

while guess_count < guess_limit:
    x = input("What's Carlos' favorite color? ")
    guess_count += 1

    if x == fav_color:
        print("You win!")
        break
    if x == fav_color2:
        print("You win!")
        break
    if x == fav_color3:
        print("You win!")
        break

Tags: youif编程countwin区分colorlimit
2条回答

使用str.lower()(或upper()

fav_color = "Red"

guess_count = 0
guess_limit = 3

while guess_count < guess_limit:
    x = input("What's Carlos' favorite color? ")
    guess_count += 1

    if x.lower() == fav_color.lower():
        print("You win!")
        break

使用.lower()string方法将输入返回的字符串转换为小写。

也就是说

fav_color = 'red'
guess_count = 0
guess_limit = 3

while guess_count < guess_limit:
    guess = input('What's Carlos' favorite color? ').lower()
    guess_count += 1
    if guess == fav_color:
        print("You win!")
        break

为了让您了解.lower()方法的工作原理,我将提供一些示例:

>>> 'Hello'.lower()
'hello'
>>> 'hello'.lower()
'hello'
>>> 'HELLO'.lower()
'hello'
>>> 'HeLLo HOW aRe YOu ToDAY?'.lower()
'hello how are you today?'

相关问题 更多 >