Skip to main content
 首页 » 编程设计

python替换数组元素中的\r\n

2025年05月04日16unruledboy

我有一个列表。其中一个元素是包含 \r\n 的大字符串。我想删除它,以便当我将元素写入新文件时,新行将在写入新列表时开始。

不知何故 replace("\r\n","") 不起作用。

例如:

['1','Smth\r\nmoretext'] 

这必须在一个新文件中:

1,smthmoretext

谢谢

请您参考如下方法:

您可以使用 list comprehensions对列表中的每个元素执行操作,并将结果放入新列表。

items = ['abc', 'abc\r\ndef', 'foo\r\n bar\r\n'] 
newItems = [s.replace('\r\n', '') for s in items] 
print newItems 
# ['abc', 'abcdef', 'foo bar']