python - .strip 不会删除某些字符串上的换行符

标签 python python-3.x strip

我正在尝试制作一个基本的登录系统,当我使用 .strip 删除从文件读取的两个字符串中的换行符 (\n) 时,它仅适用于一个字符串,即使我使用同样的事情可以从两者中删除换行符。这是我的代码。

def login():
    login_an = input("What is the name of the account you are trying to log in to?: ")
    an_file_name = login_an + ".txt"
    login_passw = input("What is the password to the account?")
    with open(an_file_name,"r") as file:
        account_name = file.readline()
        account_name.strip("\n")
        account_password = file.readline()
        account_password.strip("\n")
login()

account_name 字符串是末尾未删除换行符的字符串。我可以做什么来解决这个问题?

最佳答案

.strip() 不会就地修改字符串。它返回一个删除了空格的新字符串。您对 .strip() 的调用应如下所示:

account_name = account_name.strip("\n")

而不是

account_name.strip("\n")

关于python - .strip 不会删除某些字符串上的换行符,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/70628663/

相关文章:

Python如何根据列表中的项目从字符串中剥离字符串

python - 无法在多维列表中使用 .strip()

Python 多线程和 PostgreSQL

python - 基于按组 ID 索引的组中最大 3 个元素的新列

python - 保证哪些对象具有不同的身份?

netbeans - Netbeans 6.9.1中Python3项目调试

c++ - 如何从字符串中去除非 ASCII 字符?在 C++ 中

python - 为 QListWidget 中的特定项目设置不同的颜色

python - Python2 和 Python3 之间的 BeautifulSoup HTMLparsingError

python - 在 GAE 上,我如何根据正确的客户端时区显示日期?