我有一个看起来像下面的列表。在列表的每个项目中,单独的项目用分号分隔,但是每个分号周围的空间似乎是随机的:
['New Jersey;46.3%;Republican;03/10/2015', 'Pennsylvania;39.0%;Democrat;04/30/2012', 'Virginia;54.7%;Independent;10/25/10' ... ]
我希望最终输出是一个类似于以下内容的列表:
.split()
我一直在尝试.replace()
,但这并不是在中间放置字符。我唯一希望是在每个可能的空格和分号组合上使用{{1}}吗?
答案 0 :(得分:2)
这是一种简短的方法。这一行就足够了。
s = ['New Jersey ; 46.3% ; Republican ; 03/10/2015', 'Pennsylvania ; 39.0%; Democrat ;04/30/2012', 'Virginia . ;54.7% ;Independent ;10/25/10', 'Maryland;44.8% ; Democrat; 01/15/16', 'New York; R50.9%; Republican ; 09/22/15']
new_list = [';'.join([word.strip() for word in item.split(';')]) for item in s]
这是展开表格。
new_list = []
for item in s:
sub_list = [word.strip() for word in item.split(';')]
new_list.append(';'.join(sub_list))
print(new_list)
输出:
['New Jersey;46.3%;Republican;03/10/2015', 'Pennsylvania;39.0%;Democrat;04/30/2012', 'Virginia .;54.7%;Independent;10/25/10', 'Maryland;44.8%;Democrat;01/15/16', 'New York;R50.9%;Republican;09/22/15']
答案 1 :(得分:1)
使用replace
函数:
>>> new_list = [val.replace(' ', '') for val in old_list]
编辑:如前所述,这将删除单词“ New Jersey”中的空格。而是使用正则表达式替换:
>>> import re
>>> new_list = [re.sub(' +\.', '', re.sub(' *; *', ';', val)) for val in old_list]
>>> new_list
['New Jersey;46.3%;Republican;03/10/2015',
'Pennsylvania;39.0%;Democrat;04/30/2012',
'Virginia;54.7%;Independent;10/25/10',
'Maryland;44.8%;Democrat;01/15/16',
'New York;R50.9%;Republican;09/22/15']
答案 2 :(得分:1)
old_list = ['New Jersey ; 46.3% ; Republican ; 03/10/2015', 'Pennsylvania ;
39.0%; Democrat ;04/30/2012', 'Virginia . ;54.7% ;Independent
;10/25/10', 'Maryland;44.8% ; Democrat; 01/15/16', 'New York; R50.9%; Republican ; 09/22/15']
for row in old_list:
data = [words.strip() for words in row.split(";")]
old_list[old_list.index(row)] = ";".join(data)
答案 3 :(得分:1)
re.sub()和replace()的组合使用:
re.sub(r"\s*([;,])\s*",r"\1",txt).replace(",",", ")