Python从unicode lis中删除制表符和回车行

2024-06-10 16:16:17 发布

您现在位置:Python中文网/ 问答频道 /正文

我已经看了之前的答案(python how to remove this n from string or listremove a list item from a listpython remove whitespace in string),但无法得到有效的解决方案。

我有一个单元素列表,如下所示:

list = [u'\r\n\r\n\r\n            \r\n                \r\n                    \r\n                    123 Main St., Peoria\r\n                \r\n\r\n            \r\n             |\r\n             \r\n                    \r\n                        \r\n                            \r\n                            123-456-789\r\n                        \r\n                    \r\n            \r\n        ']

它有一个地址和一个电话号码,我只想把它寄回:

123 Main St., Peoria;123-456-789

我试过这样的东西:

str(list).strip(' \r\n\t')

以及

str(list).replace('\r','')

但它们不起作用,所以我想可能是unicode的问题?我怎样才能避开它呢?


Tags: orto答案fromstringmainthisitem
2条回答

只需从列表中取出一个元素并在其中替换:

print lst[0].replace('\r', '').replace('\n', '')

这里不需要将列表本身转换为字符串。

在这种情况下,您还可以将unicode.strip.splitlines()组合在一起以删除每一行中的空白,然后重新联接:

print u' '.join([l.strip() for l in lst[0].splitlines() if l.strip()])

这张照片:

123 Main St., Peoria | 123-456-789
import re

li = [u'\r\n\r\n\r\n \r\n \r\n \r\n 123 Main St., Peoria\r\n \r\n\r\n \r\n |\r\n \r\n \r\n \r\n \r\n 123-456-789\r\n \r\n \r\n \r\n ']
print re.sub(r'\s+', ' ', li[0].replace(' |', ';'))

印刷品

123 Main St., Peoria; 123-456-789

相关问题 更多 >