Python用.Replace命令一次替换多个字符

2024-03-28 08:43:24 发布

您现在位置: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)

有没有更好的方法?你知道吗


Tags: thein命令inputhereusername字符replace
1条回答
网友
1楼 · 发布于 2024-03-28 08:43:24

可以将^{}与包含要替换的所有字符的正则表达式一起使用:

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

相关问题 更多 >