0
Removing \n from read files at unspecified location
Tried to use this code but doesn’t work to remove \n is there something wrong with it or another method. Cant find anything online. Please also explain how it works file = open("/usercode/files/books.txt", "r") list = file.readlines() print(list[0]) for i in list: list.replace("\n", " ") print(list)
4 Respuestas
+ 1
1.
list.replace("\n", " ") to i.replace("\n", " ")
2.
replace return a new string object
list = [i.replace("\n", " ") for i in list]
3.
file.close() // at the end
+ 7
Check whether or not a line ends with '\n', if so, strip the '\n' off
...
lst = file.readlines()
for line in lst:
if line.endswith( '\n' ):
line = line.strip()
print( line )
(Edited)
Thanks Lothar for correction
+ 5
Ipang ,
there is a typo in the first line. there is dot missing.
should be:
lst = file.readlines()
^
0
fan yu thank you