在Python中分割列表
我有以下这个列表:
mylist = ['Hello,\r', 'Whats going on.\r', 'some text']
当我把“mylist”写入一个叫做 file.txt 的文件时,
open('file.txt', 'w').writelines(mylist)
我发现每一行都有一点额外的文字,这是因为有一个 \r 的原因:
Hello,
Whats going on.
some text
我该如何处理 mylist,把 \r
替换成一个空格呢?最后我需要在 file.txt
中得到这个:
Hello, Whats going on. sometext
它必须是一个列表。
谢谢!
5 个回答
0
使用 .rstrip()
方法:
>>> mylist = ['Hello,\r', 'Whats going on.\r', 'some text']
>>> ' '.join(map(str.rstrip,mylist))
'Hello, Whats going on. some text'
>>>
1
open('file.txt', 'w').writelines(map(lambda x: x.replace('\r',' '),mylist))
当然可以!请把你想要翻译的内容发给我,我会帮你用简单易懂的语言解释清楚。
5
mylist = [s.replace("\r", " ") for s in mylist]
这个代码会遍历你的列表,对每个元素进行字符串替换。