0

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?

asked Nov 2, 2018 at 23:28
2
  • 1
    Look at regular expressions (standard library module re) Commented Nov 2, 2018 at 23:44
  • FYI, replace can be chained: UserName = UserName.replace("/", "_").replace("?", "_").replace("|", "_").replace(":", "_") Commented Nov 3, 2018 at 3:10

1 Answer 1

1

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
answered Nov 2, 2018 at 23:50

Your Answer

Draft saved
Draft discarded

Sign up or log in

Sign up using Google
Sign up using Email and Password

Post as a guest

Required, but never shown

Post as a guest

Required, but never shown

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.