hac*_*man 1 python string strip punctuation
我知道我可以.translate(None, string.punctuation)从字符串中删除标点符号。但是,我想知道是否有一种方法可以仅在它是最后一个字符时才删除标点符号。
例如:
However, only strip the final punctuation.->However, only strip the final punctuation
和This is sentence one. This is sentence two!->This is sentence one. This is sentence two
和This sentence has three exclamation marks!!!->This sentence has three exclamation marks
我知道我可以编写一个while循环来执行此操作,但我想知道是否有一种更优雅/更有效的方法。
您可以简单地使用rstrip:
str.rstrip([chars])返回删除了结尾字符的字符串副本。chars参数是一个字符串,指定要删除的字符集。如果省略或为None,则chars参数默认为删除空格。chars参数不是后缀;而是删除其值的所有组合:
>>> import string
>>> s = 'This sentence has three exclamation marks!!!'
>>> s.rstrip(string.punctuation)
'This sentence has three exclamation marks'
>>> s = 'This is sentence one. This is sentence two!'
>>> s.rstrip(string.punctuation)
'This is sentence one. This is sentence two'
>>> s = 'However, only strip the final punctuation.'
>>> s.rstrip(string.punctuation)
'However, only strip the final punctuation'
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
544 次 |
| 最近记录: |