简体   繁体   中英

In Python, how can I remove characters around a specific character?

I have a list that looks like the following. Within each item of the list, separate items are delimited by a semicolon, but there the amount of space surrounding each semicolon seems to be random:

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

I would like the final output to be a list that looks like the following:

['New Jersey;46.3%;Republican;03/10/2015', 'Pennsylvania;39.0%;Democrat;04/30/2012', 'Virginia;54.7%;Independent;10/25/10' ... ]

I've been trying .split() , but that's not dropping the characters in the middle. Is doing a .replace() on each possible combination of spaces and semicolons my only hope?

Here's a short way of doing it. This one line should be enough.

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]

And here's the Expanded Form.

new_list = []

for item in s:
    sub_list = [word.strip() for word in item.split(';')]
    new_list.append(';'.join(sub_list))

print(new_list)

Outputs:

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

Use the replace function:

>>> new_list = [val.replace(' ', '') for val in old_list]

Edit: As pointed out, this removes spaces in words like "New Jersey". Instead, use a regex replace:

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

结合使用re.sub()和replace():

re.sub(r"\s*([;,])\s*",r"\1",txt).replace(",",", ")

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM