Reputation: 105
Is there any way to replace multiple different characters to another with a single .replace command?
Currently, I'm doing it once per line or through a loop:
UserName = input("Enter in Username:")
UserName = UserName.replace("/", "_")
UserName = UserName.replace("?", "_")
UserName = UserName.replace("|", "_")
UserName = UserName.replace(":", "_")
print(UserName)
#Here's the second way- through a loop.
Word = input("Enter in Example Word: ")
ReplaceCharsList = list(input("Enter in replaced characters:"))
for i in range(len(ReplaceCharsList)):
Word = Word.replace(ReplaceCharsList[i],"X")
print(Word)
Is there a better way to do this?
Upvotes: 0
Views: 110
Reputation: 12990
You can use re.sub
with a regex that contains all the characters you want to replace:
import re
username = 'goku/?db:z|?'
print(re.sub(r'[/?|:]', '_', username))
# goku__db_z__
For the case where your user enters the characters to repalce, you can build your regex as a string:
user_chars = 'abdf.#' # what you get from "input"
regex = r'[' + re.escape(user_chars) + ']'
word = 'baking.toffzz##'
print(re.sub(regex, 'X', word))
# XXkingXtoXXzzXX
Upvotes: 1