3 Way to replace multiple characters of a string at once in python
Learn how to replace multiple characters with relative values in Python. For an example in a string you want to replace character 'A' with '@', 'B' with 'b', 'c' with 'e' and 'e' with 'c' so on, you can do it in these 3 ways.
if string is : eontaet A eaBcasyAEmail.eom
Output will be : contact @ cabeasy@Email.com
Replace:
A > @
B > b
c > e
e > c
Output will be : contact @ cabeasy@Email.com
Replace:
A > @
B > b
c > e
e > c
1. Using replace() Method
new_str = str.replace('A','@').replace('B','b').replace('e','{{temp}}').replace('c','e').replace('{{temp}}','c')
print(new_str)
2. Using translate() Method
str = "eontaet A eaBcasyAEmail.eom"
# repSet = {
# 65:96, # A > @
# 66:98, # B > b
# 99:101, # c > e
# 101:99 # e > c
# }
# OR
search = "ABce"
replacewith = "@bec"
repSet = str.maketrans(search, replacewith)
new_str = str.translate(repSet)
print(new_str)
3. Create Own Custom Replace Function
str = "eontaet A eaBcasyAEmail.eom"
# @ param {String},
# @ param {searchList}, {replaceList} (in same seq.)
def multiReplace(string, searchList, replaceList):
newstr = '';
for ch in string:
if ch in searchList:
i = searchList.index(ch)
newstr += replaceList[i]
else:
newstr += ch
return newstr
new_str = multiReplace(str, ['A','B','c','e'], ['@','b','e','c'])
print(new_str)
No comments: