简体   繁体   中英

How to delete a line break character in list item python

I have a small question regarding python lists. See this code:

passwords = []
fob = open("/path/to/file", "r")
for add_items in fob :
        passwords.append(add_items)
print passwords
fob.close()

The code result:

['Monster1\n', 'Monster2\n', 'Monster3']

How to delete \\n in each add_items ?

使用rstrip('\\n')或仅使用rstrip()

passwords.append(add_items.rstrip('\n'))

You could clean it up a bit better and remove all surrounding white space by using strip . Also, you could simplify things by using a comprehension and a context manager:

with open("C:\Users\Bucky\Desktop\pass.txt") as f:
    passwords = [data.strip() for data in f]

In this answer, a context manager (the with statement) can be learned about here . That section should explain more details about the file objects and how to use a context manager.

You can use a list comprehension towether with replace to clean all instances of \\n within the string (assuming the password should not contain a carriage return):

>>> [pw.replace('\n', '') for pw in passwords]
['Monster1', 'Monster2', 'Monster3']

Above answer would work. So would this, without directly stripping each line or using list comprehension:

with open("C:\Users\Bucky\Desktop\pass.txt", "r") as fob:
    passwords = fob.read().splitlines() 

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM