[英]Removing \r\n in python
I need to remove \\r\\n on mylist. 我需要从我的列表中删除\\ r \\ n。
print mylist
>>> [1, '\r\nabc Fa 153 M Wa 3\r\n']
I did 我做了
lst = [txt.replace("\r\n", "") for txt in mylist]
but I get below error 但我得到以下错误
AttributeError: 'int' object has no attribute 'replace'
您可以使用三元表达式来跳过尝试replace
不是字符串的任何内容的尝试。
lst = [txt.replace("\r\n", "") if isinstance(txt, str) else txt for txt in mylist]
You can just strip the data from the start and end: 您可以仅从头到尾剥离数据:
l = [1, '\r\nabc Fa 153 M Wa 3\r\n']
print([x.strip() if isinstance(x, basestring ) else x for x in l ])
[1, 'abc Fa 153 M Wa 3']
A better solution would be to strip before you add the lines to the list if possible. 更好的解决方案是在可能的情况下在将行添加到列表之前先进行剥离。
Your first item is an int
and the second is a str
. 您的第一项是
int
,第二项是str
。 If you are going to have a mix of types, you could use str.strip()
in a list comprehension to handle stripping the strings. 如果要混合使用类型,则可以在列表
str.strip()
使用str.strip()
处理字符串剥离。
>>> mylist = [1, '\r\nabc Fa 153 M Wa 3\r\n']
>>> mylist = [i.strip() if isinstance(i, basestring) else i for i in mylist]
>>> mylist
[1, 'abc Fa 153 M Wa 3']
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.