简体   繁体   English

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

[英]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.

相关问题 如何在Python中用“”替换字符串中的所有标点符号? - How do I replace all punctuation in my string with “” in Python? 如何在Python中替换字符串中的标点符号? - How do I replace punctuation in a string in Python? 如何用另一个索引字符串Python替换字符串的所有实例 - How to replace all instance of a String with another indexed string Python 如何将 DataFrame 中出现的所有特定字符串替换为 Python 中的另一个字符串 - How to replace ALL particular string appear in DataFrame into another string in Python Python:删除字母数字字符串前后的所有标点符号,但字母数字字符串中的标点符号保持不变 - Python: remove all punctuation before and after a alphanumeric string, but leave punctuation within the alphanumeric string unchanged 从字符串中删除所有标点符号 - Remove all punctuation from string Python正则表达式,删除除Unicode字符串的连字符以外的所有标点符号 - Python regex, remove all punctuation except hyphen for unicode string 用另一个字符串替换一个字符串中的所有匹配项 - Replace all occurrences in a string by another string 将单词列表中的所有单词替换为python中的另一个单词 - Replace all words from word list with another string in python 在 Python 中按标点符号或数字拆分字符串 - Split string on punctuation or number in Python
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM