如何在 Python 中替换字符串中的标点符号? [英] How do I replace punctuation in a string in Python?
本文介绍了如何在 Python 中替换字符串中的标点符号?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我想在 Python 的字符串中用"替换(而不是删除)所有标点符号.
I would like to replace (and not remove) all punctuation characters by " " in a string in Python.
有没有以下风味的有效方法?
Is there something efficient of the following flavour?
text = text.translate(string.maketrans("",""), string.punctuation)
推荐答案
此答案适用于 Python 2,仅适用于 ASCII 字符串:
This answer is for Python 2 and will only work for ASCII strings:
string 模块包含两个可以帮助您的东西:标点符号列表和maketrans"函数.以下是您可以如何使用它们:
The string module contains two things that will help you: a list of punctuation characters and the "maketrans" function. Here is how you can use them:
import string
replace_punctuation = string.maketrans(string.punctuation, ' '*len(string.punctuation))
text = text.translate(replace_punctuation)
这篇关于如何在 Python 中替换字符串中的标点符号?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文