将列表的拆分字符串表示形式转换为字符串

时间:2017-09-01 05:46:41

标签: python string python-2.7 list

我已阅读删除列表中的字符'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'

由于

1 个答案:

答案 0 :(得分: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'