2012-12-19 21 views
0

我已經看過以前對此的回答(python how to remove this n from string or listremove a list item from a listpython remove whitespace in string),但無法使解決方案正常工作。Python從unicode列表中刪除製表符和運輸行

我有像這樣的單一元素的列表:

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問題?我如何解決它?

+3

不要使用'list'作爲變量名,它掩蓋了內置類型。 –

回答

3
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 
4

只取一個元素淘汰之列,並在那裏更換:

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

沒有必要列表本身在這裏轉換爲字符串。

你可以,在這種情況下,也有.splitlines()結合unicode.strip從每行中刪除空格,然後重新加入:

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

此打印:

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