Home > front end >  Remove \n character in a list without breaking apart every letter
Remove \n character in a list without breaking apart every letter

Time:12-22

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

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']

CodePudding user response:

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

CodePudding user response:

You don't need an extra for loop, just do:

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

Or don't even add these codes, just do on the first line:

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

CodePudding user response:

newList isn't a list, it's a string because you did:

newList = str(a)

There's no need to do that.

You can remove the newlines when you're reading the file:

a = [line.rstrip('\n') for line in open('NameOfFriends.txt', 'r').readlines()]

CodePudding user response:

You don't need a loop or comprehension to do it , if you want to remove only the line breaks from the text. You can use the splitlines function for that.

a = open('NameOfFriends.txt', 'r').read().splitlines()

This will do what you need.

CodePudding user response:

You can use strip() or replace() for this

replace()

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

for task in a:
    new_list.append(task.replace('\n', ''))

print(new_list)

strip()

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

for task in a:
    new_list.append(task.strip('\n'))

print(new_list)
  • Related