很难从列表中删除'\ n' [英] Hard time removing '\n' from a list

查看:75
本文介绍了很难从列表中删除'\ n'的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我很难在没有'\ n'的情况下返回我的列表。这是代码:









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)









我必须在我的列表中拆分字符串所以这就是我使用 chaine.split('/')在删除反斜杠之前。我知道在列表上操作拆分和剥离可能会很棘手,所以这就是为什么我很难过。代码正在返回:









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





如你所见,我还必须在全球清单中存储我的所有清单,以便如果你也可以帮助我,那将是很好的,但我主要专注于摆脱\ n,同时记住我必须保持.split为'/'



我的尝试:



有很多错误消息返回,因为我意识到我无法操纵像字符串这样的列表所以这就是为什么我决定使用for循环来操作列表中的每个元素。



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.

推荐答案

strip 方法只会从字符串的开头或结尾删除项目。您应该使用替换。请参见 4。内置类型 - Python 3.4.9文档 [ ^ ]。
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[^].


这篇关于很难从列表中删除'\ n'的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆