简体   繁体   中英

Removing Certain character of a element from list

If I have a list such as

List1 = ['I- m', 'I-m', 'I- m-', 'I@ am']
L2=[]
for l1 in list1:
    L2.append(l1.strip('@-'))  

How do I remove - or @ if it is connected to either word seperated by space. For example I would have to remove -@ from item 0, 2 an 3 but not 1 because Im is connected and is a same word.

Item 0, 2, and 3 have space between them.

The result should look like this:

L2=['I m','I-m', 'I m', 'I am']

However, I can remove @ from 2nd word of a item. I am unable to remove - from the first word of any item.

I hope this makes sense.

You can use re.sub to replace your characters with an empty string if there was a space in your string:

>>> [re.sub(r'[@-]',r'',i) if ' ' in i else i for i in List1]
['I m', 'I-m', 'I m', 'I am']

The best approach is to iterate a list and apply regex

import re
map(lambda x: re.sub("[\-@]([ ]|$)", "\g<1>",x), ['I- m', 'I@m', 'I-m', 'I- m-', 'I@ am'])
['I m', 'I@m', 'I-m', 'I m', 'I am']

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