Search code examples
pythonpython-3.xstrip

.strip isn't removing the newline on certain strings


I'm trying to make a basic log-in system, and when I use .strip to remove newline characters (\n) off of two strings read from a file, it works on only one string, even though I use the same thing to remove the newlines from both. Here is my code.

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()

The account_name string is the one that isn't having the newline character at the end removed. What can I do to fix this?


Solution

  • .strip() does not modify the string in-place. It returns a new string with the whitespace removed. Your calls to .strip() should look like:

    account_name = account_name.strip("\n")
    

    rather than

    account_name.strip("\n")