[英]replace all punctuation in string with another string in python
i want to replace all punctuation with string "PUNCTUATION"我想用字符串“PUNCTUATION”替换所有标点符号
. . I have many long string, so i need an efficient code.我有很多长字符串,所以我需要一个高效的代码。
for example i have some string like this例如我有一些这样的字符串
s = "Hello. World, Awesome! Really?"
i want the output to become something like this我希望 output 变成这样
replaced_s = "Hello PUNCTUATION World PUNCTUATION Awesome PUNCTUATION Really PUNCTUATION"
i think i can use replace but wont it take too long?我想我可以使用替换,但不会花费太长时间吗? any solution for this?有什么解决方案吗?
Try the string.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 '
Or use regex:或使用正则表达式:
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 '
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.