简体   繁体   中英

Python - Replace multiple character at once with .replace command

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?

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM