简体   繁体   中英

Remove items in a sequence from a string Python

Okay so I'm trying to make a function that will take a string and a sequence of items (in the form of either a list, a tuple or a string) and remove all items from that list from the string.

So far my attempt looks like this:

def eliminate(s, bad_characters):
    for item in bad_characters:
        s = s.strip(item)
    return s

However, for some reason when I try this or variations of this, it only returns either the original string or a version with only the first item in bad_characters removed.

>>> eliminate("foobar",["o","b"])
'foobar'

Is there a way to remove all items in bad_characters from the given string?

The reason your solution doesn't work is because str.strip() only removes characters from the outsides of the string, ie characters on the leftmost or rightmost end of the string. So, in the case of 'foobar' , str.strip() with a single character argument would only work if you wanted to remove the characters 'f' and 'r' .

You could eliminate more of the inner characters with strip, but you would need to include one of the outer characters as well.

>>> 'foobar'.strip('of')
'bar'
>>> 'foobar'.strip('o')
'foobar'

Here's how to do it by string-joining a generator expression:

def eliminate(s, bad_characters):
    bc = set(bad_characters)
    return ''.join(c for c in s if c not in bc)

strip is not a correct choice for this task as it remove the characters from leading and trailing of the string, instead you can use str.translate method :

>>> s,l="foobar",["o","b"]
>>> s.translate(None,''.join(l))
'far'

Try to replace the bad characters as empty strings.

def eliminate(s, bad_characters):
    for item in bad_characters:
        s = s.replace(item, '')
    return s

strip() doesn't work as it tries to remove beginning and tail part of the original string only.

Try this, may be time consuming using recursion

def eliminate(s, seq):
    while seq:
        return eliminate(s.replace(seq.pop(),""), seq)
    return s
>>>eliminate("foobar",["o","b"])
'far'

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