Python-使用.replace命令一次替换多个字符

时间:2018-11-02 23:28:08

标签: python

是否可以用一个 .replace 命令将多个不同字符替换为另一个字符?

当前,我每行或通过循环执行一次:

    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)

有没有一种更好的方法?

1 个答案:

答案 0 :(得分:0)

您可以对包含要替换的所有字符的正则表达式使用re.sub

import re

username = 'goku/?db:z|?'
print(re.sub(r'[/?|:]', '_', username))
# goku__db_z__

对于用户输入要重新输入的字符的情况,您可以build your regex作为字符串:

user_chars = 'abdf.#' # what you get from "input"
regex = r'[' + re.escape(user_chars) + ']'

word = 'baking.toffzz##'
print(re.sub(regex, 'X', word))
# XXkingXtoXXzzXX