3

Is there a simple way in python to replace multiples characters by another?

For instance, I would like to change:

name1_22:3-3(+):Pos_bos 

to

name1_22_3-3_+__Pos_bos

So basically replace all "(",")",":" with "_".

I only know to do it with:

str.replace(":","_")
str.replace(")","_")
str.replace("(","_")

4 Answers 4

9

You could use re.sub to replace multiple characters with one pattern:

import re
s = 'name1_22:3-3(+):Pos_bos '
re.sub(r'[():]', '_', s)

Output

'name1_22_3-3_+__Pos_bos '
Sign up to request clarification or add additional context in comments.

Comments

6

Use a translation table. In Python 2, maketrans is defined in the string module.

>>> import string
>>> table = string.maketrans("():", "___")

In Python 3, it is a str class method.

>>> table = str.maketrans("():", "___")

In both, the table is passed as the argument to str.translate.

>>> 'name1_22:3-3(+):Pos_bos'.translate(table)
'name1_22_3-3_+__Pos_bos'

In Python 3, you can also pass a single dict mapping input characters to output characters to maketrans:

table = str.maketrans({"(": "_", ")": "_", ":": "_"})

Comments

3

Sticking to your current approach of using replace():

s =  "name1_22:3-3(+):Pos_bos"
for e in ((":", "_"), ("(", "_"), (")", "__")):
    s = s.replace(*e)
print(s)

OUTPUT:

name1_22_3-3_+___Pos_bos

EDIT: (for readability)

s =  "name1_22:3-3(+):Pos_bos"
replaceList =  [(":", "_"), ("(", "_"), (")", "__")]

for elem in replaceList:
    print(*elem)          # : _, ( _, ) __  (for each iteration)
    s = s.replace(*elem)
print(s)

OR

repList = [':','(',')']   # list of all the chars to replace
rChar = '_'               # the char to replace with
for elem in repList:
    s = s.replace(elem, rChar)
print(s)

Comments

2

Another possibility is usage of so-called list comprehension combined with so-called ternary conditional operator following way:

text = 'name1_22:3-3(+):Pos_bos '
out = ''.join(['_' if i in ':)(' else i for i in text])
print(out) #name1_22_3-3_+__Pos_bos

As it gives list, I use ''.join to change list of characters (strs of length 1) into str.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.