在 Python 2.x 中去除特定标点符号 [英] Strip Specific Punctuation in Python 2.x
问题描述
我使用的是 Python v2.6,我有一个字符串,其中包含许多我想删除的标点符号.现在我已经考虑使用 string.punctuation()
函数,但不幸的是,我想去掉除句号和破折号之外的所有标点字符.总共只有 5 个标点符号我想去掉 - ()\"'
有什么建议吗?我希望这是最有效的方式.
谢谢
您可以使用 str.translate(table[, deletechars])
将 table
设置为 None
,这将导致 None
中的所有字符代码>deletechars 被从字符串中删除:
s.translate(None, r"()\"'")
一些例子:
<预><代码>>>>"\"你好\" '(world)'".translate(None, r"()\"'")'你好,世界'>>>"a'b c\"d e(f g)h i\\j".translate(None, r"()\"'")'ab cd ef gh ij'I'm using Python v2.6 and I have a string which contains a number of punctuation characters I'd like to strip out. Now I've looked at using the string.punctuation()
function but unfortunately, I want to strip out all punctuation characters except fullstops and dashes. In total, there are only a total of 5 punctuation marks I'd like to strip out - ()\"'
Any suggestions? I'd like this to be the most efficient way.
Thanks
You can use str.translate(table[, deletechars])
with table
set to None
, which will result in all characters from deletechars
being removed from the string:
s.translate(None, r"()\"'")
Some examples:
>>> "\"hello\" '(world)'".translate(None, r"()\"'")
'hello world'
>>> "a'b c\"d e(f g)h i\\j".translate(None, r"()\"'")
'ab cd ef gh ij'
这篇关于在 Python 2.x 中去除特定标点符号的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!