Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Remove \n character in a list without breaking apart every letter

I am trying to remove ‘\n’ from the end of each element in a list imported from a .txt file

Here is the file I am importing:

NameOfFriends.txt
Joeseph
Mary
Alex

Here is the code I am running

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

a = open('NameOfFriends.txt', 'r').readlines()

print(a)

newList = str(a)

print(type(newList[0]))

for task in newList:
    newList = [task.replace('\n', '') for task in newList]

print(newList)

Here is the output:

['Joeseph\n', 'Mary\n', 'Alex']
<class 'str'>
['[', "'", 'J', 'o', 'e', 's', 'e', 'p', 'h', '\\', 'n', "'", ',', ' ', "'", 'M', 'a', 'r', 'y', '\\', 'n', "'", ',', ' ', "'", 'A', 'l', 'e', 'x', "'", ']']

Here is the desired output when variable newList is printed:

['Joeseph', 'Mary', 'Alex']

>Solution :

with open('NameOfFriends.txt') as file:
    names = []
    for name in file.readlines():
        names.append(name.strip("\n"))
    print(names)
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading