-1

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

Alberto Aguilera
  • 311
  • 1
  • 5
  • 13

2 Answers2

2

Use str.translate.

>>> word = "word"
>>> to_delete = ["w","r"]
>>> 
>>> trans = str.maketrans(dict.fromkeys(to_delete))
>>> word.translate(trans)
'od'
timgeb
  • 76,762
  • 20
  • 123
  • 145
2

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.

Maximilian Burszley
  • 18,243
  • 4
  • 34
  • 63