Click here to Skip to main content
14,024,683 members
Rate this:
 
Please Sign up or sign in to vote.
See more:
Im having a hard time returning my list without the '\n'. Here's the code :




evenement =  open("evenements.txt", "r", encoding="utf-8-sig")

liste = []
chaine = ""

for line in evenement:
    chaine += line

chaine_split = chaine.split('/')

for element in chaine_split:
    liste.append(element.strip('\n'))

print(liste)




I had to split the strings in my list so this is why im using chaine.split('/') before removing the backslash. I know it can be tricky to manipulate split and strip on lists so this is why im having a hard time. Code is returning :


['Musique', 'Shawn Phillips', '2018-08-24', '2018-08-24\nMusique', "L'avenue Royale fête l'été!", '2018-08-25', '2018-08-25\nMusique', 'Perséides musicales', '2018-08-03', '2018-08-03\n.... 


but has to return :

[['Musique', 'Shawn Phillips', '2018-08-24', '2018-08-24] 
[Musique', "L'avenue Royale fête l'été!", '2018-08-25', '2018-08-25]
[Musique', 'Perséides musicales', '2018-08-03', '2018-08-03]]


As you can see i also have to stock all my lists in a global list so it would be nice if you could help me with that too, but im mostly focusing on getting rid of the \n while keeping in mind that i have to keep the .split for the '/'.

What I have tried:

Had a lot of error messages returned because i realised i couldnt manipulate a list like a string so this is why i decided to use a for loop to manipulate each element of my list.
Posted
Updated 10-Oct-18 21:56pm

1 solution

Rate this: bad
 
good
Please Sign up or sign in to vote.

Solution 1

The strip method will only remove items from the beginning or end of the string. You should use replace. See 4. Built-in Types — Python 3.4.9 documentation[^].
   
Comments
Member 13870077 11-Oct-18 12:48pm
   
But can you use replace on a list? I assume i do as long as i use a loop ?
Richard MacCutchan 11-Oct-18 12:50pm
   
You could use a list comprehension, or just do it in the loop that you already have above.
Member 13870077 11-Oct-18 12:53pm
   
Okay thanks and what about split, does it work on a list
Richard MacCutchan 11-Oct-18 13:00pm
   
All depends on what you are trying to do. The best way to find out is to try a few experiments with made up data.

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)

  Print Answers RSS
Top Experts
Last 24hrsThis month


Advertise | Privacy | Cookies | Terms of Service
Web02 | 2.8.190419.4 | Last Updated 11 Oct 2018
Copyright © CodeProject, 1999-2019
All Rights Reserved.
Layout: fixed | fluid

CodeProject, 503-250 Ferrand Drive Toronto Ontario, M3C 3G8 Canada +1 416-849-8900 x 100