如何在同一循环中同时添加lower()和strip()

2024-06-01 07:26:03 发布

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

我是个新手,但我想学得快一点。你知道吗

代码如下:

current_users = ['john', '    Bimu', 'admin              ', 'royo', 'AbCdEf', 'popo']

current_users = [current_users.strip() for current_users in current_users]

current_users = [current_users.lower() for current_users in current_users]

new_users = ['astra', '   JOHN', 'RoYO', ' gfgf', 'toui       ', '     popo']

new_users_stripped = new_users[:]

for new_user in new_users:

    if new_user.strip() not in current_users:

        print("Username " + new_user + " is available")

    else:

         print("Username " + new_user + " is already taken. You will need "
                "to chose another username")

我想剥离和降低的数据,但要显示原来的用户名在最后回来。我也希望我的代码更干净。到目前为止,我已经能够剥离()或降低(),但无法做到这两个。我仍然在这个问题上运行,在我看来它应该在循环中运行,但我不知道如何运行。你知道吗

有人能帮忙吗?谢谢!你知道吗


Tags: 代码innewforisusernamecurrentjohn
2条回答

如果你想保留原件,那么你应该复制一份原件,并且只对副本进行修改。这样您就拥有了原始用户名和修改后的用户名。你知道吗

我必须current_users成为set的一员,以使搜索更高效。你知道吗

current_users = ['john', '    Bimu', 'admin              ', 'royo', 'AbCdEf', 'popo']

current_users = set(user.strip().lower() for user in current_users)

new_users = ['astra', '   JOHN', 'RoYO', ' gfgf', 'toui       ', '     popo']

for user in new_users:
    if user.strip().lower() in current_users:
        print("Username {} is available".format(user))
    else:
        print("Username {} is not available".format(user))

这里我们不保存user.strip().lower()的结果,所以旧值仍然存储在user

相关问题 更多 >