【问题标题】:Punctuation Replacement Python标点替换 Python
【发布时间】:2026-01-13 05:25:01
【问题描述】:

学习 python 并且似乎无法弄清楚为什么我的代码不起作用,我试图用空格替换给定字符串中的所有标点符号。这是我的代码...

import string 

def replace(text):

    for char in text:
        if char in string.punctuation:
            text.replace(char, " ")

    return text 




test = "Ok! Where, to now?"


#expected "Ok  Where  to now  " 
#returned "Ok! Where to now?" 

感谢任何输入!谢谢!

【问题讨论】:

    标签: python string methods replace


    【解决方案1】:

    作为关于效率的说明,python 将在每次调用 text.replace 时创建整个字符串的新副本。更好的选择是将事物字符串转换为字符列表,然后就地修改列表。

    char_list = list(txt)
    for i, char in enumerate(char_list):
        if char in string.punctuation:
             char_list[i] = " "
    return "".join(char_list)
    

    最好还是使用字符串模块翻译功能:

    import string
    x = 'this.! is my ^$input string?'
    trans_tab = string.maketrans(string.punctuation, ' ' * len(string.punctuation))
    print string.translate(x, trans_tab)
    print x
    print string.translate(x, None, string.punctuation)
    

    输出:

    this   is my   input string 
    this.! is my ^$input string?
    this is my input string
    

    请注意,翻译功能会生成副本,不会修改您的原始字符串。

    【讨论】:

      【解决方案2】:

      replace 不会修改传递给第一个参数的字符串(string 对象是不可变的,这意味着对象本身不能被修改)。所以你需要自己用替换操作的返回值更新text变量:

      text = text.replace(char, " ")
      

      来自documentation(强调我的):

      返回字符串 s 的副本,其中所有出现的子字符串 old 都替换为 new。如果给出了可选参数 maxreplace,则替换第一个 maxreplace 出现。

      【讨论】: