I would like to delete from a string all the characters from a list.
For example:
to_delete = ["w","r"]
word = "word"
word.replace(to_delete,'')
>> od
What is the best/fast solution to do it? Is it possible without loops?
Thanks in advance
I would like to delete from a string all the characters from a list.
For example:
to_delete = ["w","r"]
word = "word"
word.replace(to_delete,'')
>> od
What is the best/fast solution to do it? Is it possible without loops?
Thanks in advance
Use str.translate
.
>>> word = "word"
>>> to_delete = ["w","r"]
>>>
>>> trans = str.maketrans(dict.fromkeys(to_delete))
>>> word.translate(trans)
'od'
I'd suggest regex:
import re
word = "word"
to_delete = ['w', 'r']
re.sub(f"[{''.join({re.escape(i) for i in to_delete})}]", '', word)
This will join your characters to replace into a regex set pattern for replacement, takes the word as input, and replaces those characters with empty strings.