Home > Software engineering >  Python, Removing New Line in List
Python, Removing New Line in List

Time:09-27

I have the following Codesample:

Codesample:

import string
import fileinput
Path = '/Volumes/test_copy.txt'

#/I
filename = Path
with open(filename) as file_object:
     lines = file_object.readlines()

mylists = [item   "ENDTOKEN"   for item in lines]
mylists2 = ["STARTTOKEN"   item   "ENDTOKEN"   for item in lines] 

#/O
print(mylists)
print(mylists2)

Content of test_copy.txt:

textprompt     nextelement

Output:

textprompt     nextelement
ENDTOKEN

STARTTOKENtextprompt     nextelement
ENDTOKEN

Preferred Output:

STARTTOKENtextprompt     nextelementENDTOKEN # 1. Pref.
STARTTOKENtextprompt     nextelement ENDTOKEN # 2. Pref.

So far the newline only occurs in the after ' ' So the Python mechanism of newlines.

Is there anyway to change the list properties? I'm also aware of the same issue for print(), but i know how to fix it there with more '''.

Edit: However, I'd like to have the lists cleaner. Printing out list[0] does print it also with \n

I have also tryed conditions, behind the comprehension with "\n" or " ".

Changed 'list' to ‘mylists‘. Thx to rockzxm & BeRT2me here.

Solved by BeRT2me

Thanks in advance!

CodePudding user response:

test.txt

textprompt   otherstuff
nexttextprompt  morestuffs

Doing:

with open('deleteme.txt') as f:
    # Either of these methods eliminate the new lines at the end.
    lines = f.read().splitlines()
    # OR
    # lines = [x.rstrip('\n') for x in f.readlines()]

output = ["STARTTOKEN"   item   "ENDTOKEN" for item in lines]

# We can print like you want like so:
print(*output, sep='\n')

# But it seems like maybe you actually want a string:
output = '\n'.join(output)
print(output)

Output (The same both times):

STARTTOKENtextprompt   otherstuffENDTOKEN
STARTTOKENnexttextprompt  morestuffsENDTOKEN
  • Related