'Replace function, how to assign "b" multiple values? [closed]

My problem is very small, and is that I can't do a normal letter substitution. I know the .replace command, but I can't seem to use it correctly.

For example: My k##yb0%%rd is br###k##n. ### should be replaced with o, ## with e, and %% with a. Thanks!

a = input("What did she say? ")
b = a.replace("###", "o")
print(b)


Solution 1:[1]

You can try something like this:

a = input("What did she say? ")
d = {'###':'o', '##':'e','%%':'a'}
for k,v in d.items():
    a = a.replace(k, v)
b = a # if you need value in b variable
print(b)

You can create such dictionary and use it replace multiple values. Make sure to properly arrange your dictionary.

Solution 2:[2]

As the first thing I would suggest to read the Python's documentation for str.replace.


I would suggest something like this:

b = a.replace("###", 'o').replace("##", 'e').replace("%%", 'a')

This is possible because the returned value of a.replace("###", 'o') is of type str, so that the method replace can be applied on it too.


If you don't know which characters will be replaced, you should do like suggested by Vaibhav, creating a dict that associates old chars (key) with new chars (value).


What's more str is an immutable type, so you can't just do

a.replace("###", 'o').replace("##", 'e').replace("%%", 'a')

but anyway you don't have to assign the returned value to b, you can't reassign it to a without problems:

a = a.replace("###", 'o').replace("##", 'e').replace("%%", 'a')

and you can print it directly too.

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 Vaibhav Jadhav
Solution 2