Python 如何进行不区分大小写的字符串比较?

Python 如何进行不区分大小写的字符串比较?,python,Python,对于需要不区分大小写输入的Python练习,我有点困惑 这部分让我困惑的练习: 确保比较不区分大小写。如果使用了“John”,则不应接受“John” 这是我的密码: current_users = ['username_1', 'username_2', 'username_3', 'username_4', 'username_5'] new_user = ['new_user_1', 'new_user_2', 'new_user_3', 'username

对于需要不区分大小写输入的Python练习,我有点困惑

这部分让我困惑的练习:

确保比较不区分大小写。如果使用了“John”,则不应接受“John”

这是我的密码:

current_users = ['username_1', 'username_2', 'username_3', 'username_4',
                 'username_5']
new_user = ['new_user_1', 'new_user_2', 'new_user_3', 'username_1', 'Username_2']

for username in new_user:
    if username in current_users:
        print("Please enter a new username.")
    elif username not in current_users:
        print("This username is available.")
我的问题是,我试图让我的代码拒绝“Username_2”,因为大写字母“U”,但我不知道如何做到这一点。我正在阅读Eric Matthes的Python速成课程,目前正在阅读第5章,但我不记得有人教我如何拒绝不区分大小写的输入

我知道
upper()
lower()
title()
字符串方法,并尝试使用:

username.lower() == username.upper()

new_user.lower() == new_user.upper()

在我的
for
循环之前,但这只会导致语法错误。

您可以将每个新用户名转换为小写,并将其与用户列表的小写版本(使用列表理解创建)进行比较


您可能希望在首次创建用户名时以小写形式存储用户名,以避免从用户列表中创建小写版本。

您可以将每个新用户名转换为小写,并将其与用户列表的小写版本(使用列表创建)进行比较


您可能希望在首次创建用户名时将其存储为小写,以避免从用户列表中创建小写版本。

Btw,您可以将
elif username not in current_users:
替换为
else:
,因为如果
username in current_users
返回true,则总是会失败。似乎您需要区分大小写的比较,以便“John”不会被视为与“John”相同,并且Python字符串相等性测试,
=
,默认情况下,运算符中的
都区分大小写。这可能是个骗人的问题吗?顺便说一句,您可以将
elif username not in current_users:
替换为
else:
,因为如果
username in current_users
返回true,则总是会失败。似乎您需要区分大小写的比较,以便“John”不会被视为与“John”相同,并且Python字符串相等性测试,
=
,默认情况下,
运算符中的
都区分大小写。这可能是个骗人的问题吗?
lower_case_users = [user.lower() for user in current_users]
if new_user.lower() in lower_case_users:
    # Name clash