lost and found ( for me ? )

Python : remove ‘\n’ from a list

small tips.

You can delete ‘\n’ with rstrip method like this.

read a text file, put those into a list, remove ‘\n’.
# cat a.txt
hello
cheers
nice
good
bye

# python
>>> f = open('a.txt')
>>>
>>> list = f.readlines()
>>>
>>> list
['hello\n', 'cheers\n', 'nice\n', 'good\n', 'bye\n']
>>>
>>> list2 = []
>>>
>>> for i in list:
...     list2.append(i.rstrip('\n'))
...
>>>
>>> list2
['hello', 'cheers', 'nice', 'good', 'bye']
>>>

No comments:

Post a Comment

Note: Only a member of this blog may post a comment.