python - 在 Python 中,如何删除特定字符周围的字符?

标签 python list strip

我有一个如下所示的列表。在列表的每个项目中,单独的项目由分号分隔,但每个分号周围的空间量似乎是随机的:

['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 Jersey;46.3%;Republican;03/10/2015', 'Pennsylvania;39.0%;Democrat;04/30/2012', 'Virginia;54.7%;Independent;10/25/10' ... ]

我一直在尝试 .split(),但这并没有将字符放在中间。我唯一的希望是对空格和分号的每种可能组合执行 .replace() 吗?

最佳答案

这是一个简短的方法。一行就够了。

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']

关于python - 在 Python 中,如何删除特定字符周围的字符?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53195306/

相关文章:

python - 在 matplotlib 中绘制双变量高斯分布

python - pytest 2.3 中的包范围固定装置

python - swig numpy 多矩阵和数组输入

java - 使用LinkedList的迭代器打印值,在java中不断陷入无限循环

python - 如何将其打印为新列表?

plot - 在 Stata 中创建 seaborn stripplot

linux-kernel - 如何从 linux 内核模块中去除本地符号而不破坏它?

python - 错误 : PerfectSeparationError: Perfect separation detected, 结果不可用

python - 将列表的列表转换为一个大列表python

Bash 脚本中的 Linux SED 命令从字符串中剥离 '