如何在Python中替换字符串中的标点符号

2024-05-16 23:22:53 发布

您现在位置:Python中文网/ 问答频道 /正文

我想用Python中的一个字符串中的“”替换所有标点字符。

有什么有效的下列味道吗?

text = text.translate(string.maketrans("",""), string.punctuation)

Tags: 字符串textstring字符translatepunctuation味道标点
3条回答

有一个更健壮的解决方案依赖于regex排除,而不是通过大量标点字符列表包含。

import re
print(re.sub('[^\w\s]', '', 'This is, fortunately. A Test! string'))
#Output - 'This is fortunately A Test string'

regex捕获不是字母数字或空白字符的任何内容

这个答案是针对Python 2的,只适用于ASCII字符串:

string模块包含两个可以帮助您的东西:标点符号列表和“maketrans”函数。下面是如何使用它们的:

import string
replace_punctuation = string.maketrans(string.punctuation, ' '*len(string.punctuation))
text = text.translate(replace_punctuation)

来自Best way to strip punctuation from a string in Python的改性溶液

import string
import re

regex = re.compile('[%s]' % re.escape(string.punctuation))
out = regex.sub(' ', "This is, fortunately. A Test! string")
# out = 'This is  fortunately  A Test  string'

相关问题 更多 >