Replace multiple characters using replace ()

How to replace multiple characters with a method replace()? Is there only one way to do this replace()? Or are there any better ways?

The symbols may look like this, for example -, +, /, ', ., &.

+4
source share
4 answers

You can use re.suband put characters in a character class :

import re
re.sub('[-+/\'.&]', replace_with, input)
+5
source

You can do this by using str.joinwith a generator expression (without importing any library) like:

>>> symbols = '/-+*'
>>> replacewith = '.'
>>> my_text = '3 / 2 - 4 + 6 * 9'  # input string

#  replace char in string if symbol v
>>> ''.join(replacewith  if c in symbols else c for c in my_text)
'3 . 2 . 4 . 6 . 9'   # Output string with symbols replaced
+2
source
# '7' -> 'A', '8' -> 'B'
print('asdf7gh8jk'.replace('7', 'A').replace('8', 'B'))
+1

, , :

string = 'abc'
old = ['a', 'b', 'c']
new = ['A', 'B', 'C']
for o, n in zip(old, new):
    string = string.replace(o, n)

print string
>>> 'ABC'
+1

Source: https://habr.com/ru/post/1663772/


All Articles