用 python 中的另一个字符串替换字符串中的所有标点符号

replace all punctuation in string with another string in python

我想用字符串替换所有标点符号 "PUNCTUATION"

。我有很多长字符串,所以我需要一个高效的代码。

例如我有这样的字符串

s = "Hello. World, Awesome! Really?"

我希望输出变成这样

replaced_s = "Hello PUNCTUATION World PUNCTUATION Awesome PUNCTUATION Really PUNCTUATION"

我想我可以使用替换但不会花太长时间吗? 有什么解决办法吗?

尝试 string.punctuation

import string
s = "Hello. World, Awesome! Really?"
for c in string.punctuation:
    s = s.replace(c,' PUNCTUATION ')
s
#'Hello PUNCTUATION  World PUNCTUATION  Awesome PUNCTUATION  Really PUNCTUATION '

或使用正则表达式:

import re
s = "Hello. World, Awesome! Really?"
s = re.sub(r'[^\w\s]',' PUNCTUATION ',s)
re.sub(' +', ' ',s)
#'Hello PUNCTUATION World PUNCTUATION Awesome PUNCTUATION Really PUNCTUATION '