2

I had a list that read from a text file into an array but now they all have "\n" on the end. Obviously you dont see it when you print it because it just takes a new line. I want to remove it because it is causing me some hassle.

database = open("database.txt", "r") databaselist = database.readlines() 

thats the code i used to read from the file. I am a total noob so please dont use crazy technical talk otherwise it will go straight over my head

0

2 Answers 2

3
"string with or without newline\n".rstrip('\n') 

Using rstrip with \n avoids any unwanted side-effect except that it will remove multiple \n at the end, if present.

Otherwise, you need to use this less elegant function:

def rstrip1(s, c): return s[:-1] if s[-1]==c else s 
Sign up to request clarification or add additional context in comments.

1 Comment

+1 for mentioning the correct way of using it in this case. Mentioning some of the side effects: using strip() without arguments will also remove any trailing white spaces or tabs \t.
1

Use str.rstrip to remove the newline character at the end of each line:

databaselist = [line.rstrip("\n") for line in database.readlines()] 

However, I recommend that you make three more changes to your code to improve efficiency:

  1. Remove the call to readlines. Iterating over a file object yields its lines one at a time.

  2. Remove the "r" argument to open since the function defaults to read-mode. This will not improve the speed of your code, but it will make it less redundant.

  3. Most importantly, use a with-statement to open the file. This will ensure that it is closed automatically when you are done.

In all, the new code will look like this:

with open("database.txt") as database: databaselist = [line.rstrip("\n") for line in database] 

1 Comment

.rstrip('\n') in case it is a tab-delimited database with a blank field at the end (\t\n)

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.