2017-09-01 133 views
0

我已經閱讀了關於刪除列表中的字符「U」,但它並不在我的情況下工作:如果我使用轉換列表的分割字符串表示爲一個字符串

[u"[u'DUTY,", u'RHODE', u'ISLAND', u'STATE', u'ASSOCIATION', u'OF', u'FIRE', u"OF']"] 

**Expected Output** : DUTY RHODE ISLAND STATE ASSOCIATION OF FIRE OF 

list = [u"[u'DUTY,", u'RHODE', u'ISLAND', u'STATE', u'ASSOCIATION', u'OF', u'FIRE', u"OF']"] 

new_list = "%s, %s" % (list[-1], ' '.join(list[:-1])) 

Output will : u"OF'], [u'DUTY, RHODE ISLAND STATE ASSOCIATION OF FIRE FIGHTERS LINE" 

如果

next_list = [str(' '.join(filter(None, new_list)))] 
Output is: ["[u'DUTY, RHODE ISLAND STATE ASSOCIATION OF FIRE FIGHTERS LINE OF']"] 

如果:

import ast 
ast.literal_eval(' '.join(list))[0] 

Output is : u'DUTY, RHODE ISLAND STATE ASSOCIATION OF FIRE FIGHTERS LINE OF' 

感謝

+0

我想這回答你的問題。 https://stackoverflow.com/questions/1207457/convert-a-unicode-string-to-a-string-in-python-containing-extra-symbols –

+0

@KamiloVasquezCaro還有額外的u作爲列表中的前綴 –

回答

1

你應該能夠迅速做到這一點使用ast.literal_eval

import ast 

s = ["[u'DUTY,", 'RHODE', 'ISLAND', 'STATE', 'ASSOCIATION', 'OF', 'FIRE', "OF']"] 
out = ast.literal_eval(' '.join(s))[0] 

print(str(out)) # the str bit is redundant for python3 
'DUTY, RHODE ISLAND STATE ASSOCIATION OF FIRE OF' 
+0

使用你的方法的輸出是:u'DUTY,羅德島州消防隊聯合會' –

+0

'列表中還有額外的你在列表 –

+0

@SNTiwari Run'out = str(out);打印(出)' –