【问题标题】:How to check if only a part of a variable is next to a string in Python?如何检查Python中是否只有一部分变量位于字符串旁边?
【发布时间】:2026-01-23 10:40:01
【问题描述】:

我正在尝试让我的代码检查文档中是否已经存在某个单词。但是,在选择变量(username)时@遇到与文件中的预先存在的相同字母相同的字母,它认为该名称是拍摄的。例如,如果abcdefg 在文件中,如果我要对defgfgg,它会认为用户名已被占用。

def register():
    print("━━━━ACCOUNT CREATION━━━━")
    username = input("Create Username: ")
    with open("Login.txt", "r") as loginfile:
        if (username+",") in loginfile.read():
            print("Sorry, but that username is taken.")
            choice = input("Try again with a new name? (Y/N)")
            choice = choice.upper()

我的情况: 假设我有名字,Joe,它已经在文件中。如果我尝试创建一个只是 e 的用户名,那么它会认为是 Joe,因为它正在寻找逗号旁边的 e。

无论如何要解决这个问题?谢谢!

【问题讨论】:

  • 你试过使用正则表达式吗?
  • 欢迎来到 SO。请添加一个示例,说明您的 Login.txt 文件的结构。
  • 嗨 ScootCork,该文件非常基本,结构如下:名称、密码

标签: python string file


【解决方案1】:

这应该可以工作

with open('login.txt', 'r') as LoginFile:
    # the split function splits a string to a list on mark
    Data = LoginFile.read().split(" ,") 
    if username in Data:
        # .....

如果这不是你想要的,试试这个内置模块:

https://docs.python.org/3/library/re.html

【讨论】:

  • 感谢您的回复,这行得通,但后来成功了,所以可能有两个帐户具有相同的用户名。不过还是感谢您的贡献!
【解决方案2】:
def register():
    print("━━━━ACCOUNT CREATION━━━━")

    # read the names from the file
    with open('Login.txt', 'r') as f:
        names = f.read().split(',')

    username = input("Create Username: ")

    for name in names:
        # check if any names end with this name have been created
        if name.endswith(username):
            # found
            print("Sorry, but that username is taken.")

            # we want to keep ask the user to select if
            # they enter something other than Y/N
            while True:
                # ask for the option
                option = input("Try again with a new name? (Y/N) ")
                # try again, we just rerun this function
                if option == 'Y':
                    register()
                    # don't ask any more
                    break
                elif option == 'N':
                    # exit if user chooses N
                    break
                # if the user chooses something else, continue
                # the loop and keep asking
                
            # if no names end with username, goto else
            break
    else:
        # name available, save it to the file
        print("Name created successfully:", username)
        new_names = names + [username]
        with open('Login.txt', 'w') as f:
            f.write(','.join(new_names))

我已经测试过了,请尝试看看它是否适合你。

【讨论】:

  • 我认为这行得通。但是,不幸的是,我不够聪明,无法实现这一点。不过我还是会标记为正确的。
  • @Fiery 没问题。试着测试一下。如果您有任何问题,请随时告诉我。
  • 我刚试了一下,还是不行:(。我把名字设为joe,下次我试的时候,我把名字设为e,它仍然说它被占用了: O. 你知道如何解决这个问题,还是与 (r'\b([\w\d_]*' + username + r) 有关,因为我知道这些是什么意思,哈哈。谢谢!
  • 您是否也想将用户创建的名称保存到Login.txt,以便下次报告为被占用?或者您能否逐步详细说明目标?例如,输入不同名称时的行为是什么?我其实有点困惑。
  • 感谢您的回复!我已经可以将它们保存到文件中以备下次使用,但是我坚持的一点是检查变量。这是因为我的方法是检查用户名是否在逗号旁边。这是因为那是txt文档的布局。我的问题是,它检查它是否在逗号旁边,但是当它检查用户名是否在逗号旁边时,如果它是另一个用户名的结尾,那么它会认为它在文件中并说用户名是采取。
最近更新 更多