如何用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
相关产品推荐
相关产品推荐

