首页
学习
活动
专区
圈层
工具
发布
首页
学习
活动
专区
圈层
工具
社区首页 >问答首页 >如何仅当是最后一个字符时才能删除点字

如何仅当是最后一个字符时才能删除点字
EN

Stack Overflow用户
提问于 2017-09-30 16:28:42
回答 2查看 826关注 0票数 1

我知道我可以用.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循环来完成这个任务,但是我想知道是否有一种更优雅、更有效的方法。

EN

回答 2

Stack Overflow用户

回答已采纳

发布于 2017-09-30 16:30:46

您可以简单地使用rstrip

str.rstrip([chars]) 返回字符串的副本,并删除尾随字符。chars参数是一个字符串,指定要删除的字符集。如果省略或没有,chars参数默认为删除空格。chars参数不是后缀;相反,其值的所有组合都被删除:

代码语言:javascript
代码运行次数:0
运行
复制
>>> 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'
票数 5
EN

Stack Overflow用户

发布于 2017-09-30 17:16:15

re.sub(r'[,;\.\!]+$', '', 'hello. world!!!')

票数 -1
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/46504753

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档