You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何用Python的replace()函数实现去除单词中所有标点的功能?

解决字符串批量去除标点的问题

你的代码目前只能去掉一种标点,核心问题是每次替换都用原始输入的word变量,而非已经处理过的字符串,而且循环结束后只保留最后一次替换的结果,自然没法把所有标点都去掉。

修正后的代码如下:

punctuation_chars = ['\'', '"', ',', '.', '!', ':', ';', '#', '@']
def strip_punctuation(word):
    # 初始化清理后的字符串为输入值
    cleaned_word = word
    # 遍历所有标点字符,逐个替换为空
    for punct in punctuation_chars:
        cleaned_word = cleaned_word.replace(punct, "")
    # 去除首尾空白(对应示例输入的开头空格)
    return cleaned_word.strip()

y = strip_punctuation("#incr!edible")
print(y)  # 输出: incredible

说明:

  • 用cleaned_word变量持续保存处理后的结果,每次替换都基于上一次的结果操作,确保所有标点被逐步清除
  • 遍历标点列表比遍历字符串字符更高效,因为标点数量固定且很少
  • 最后加strip()是为了处理示例输入里的首尾空格,如果你不需要去除空格,可以删掉这部分

内容的提问来源于stack exchange,提问作者Arafat Farjid

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.19 19:45:34