Warning: file_get_contents(/data/phpspider/zhask/data//catemap/0/asp.net-mvc/17.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Python 如何仅在其';最后一个字符是什么_Python_String_Strip_Punctuation - Fatal编程技术网

Python 如何仅在其';最后一个字符是什么

Python 如何仅在其';最后一个字符是什么,python,string,strip,punctuation,Python,String,Strip,Punctuation,我知道我可以使用.translate(无,字符串.标点符号)从字符串中去除标点符号。然而,我想知道是否有一种方法可以去除标点符号,只要它是最后一个字符 例如: 但是,仅去除最后一个标点。->但是,仅去除最后一个标点 这是第一句话。这是第二句->这是第一句话。这是第二句 这个句子有三个感叹号->这个句子有三个感叹号 我知道我可以写一个while循环来实现这一点,但我想知道是否有更优雅/高效的方法。您可以简单地使用: str.rstrip([chars]) 返回已删除尾随字符的字符串副本。chars

我知道我可以使用
.translate(无,字符串.标点符号)
从字符串中去除标点符号。然而,我想知道是否有一种方法可以去除标点符号,只要它是最后一个字符

例如:
但是,仅去除最后一个标点。
->
但是,仅去除最后一个标点

这是第一句话。这是第二句->
这是第一句话。这是第二句

这个句子有三个感叹号->
这个句子有三个感叹号

我知道我可以写一个while循环来实现这一点,但我想知道是否有更优雅/高效的方法。

您可以简单地使用:

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

您可以简单地使用:

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


re.sub(r'[,;\.\!]+$,''hello.world!!!')
re.sub(r'[,;\.\!]+$,''hello.world!!!')
虽然这段代码可以回答这个问题,但可能最好包含更多的上下文/解释。好吧,它足够简单。只需调用
re.sub()
方法,使用一个正则表达式删除字符串末尾的标点符号-与所写的完全相同。虽然此代码可能会回答问题,但最好包含更多上下文/解释。好吧,它足够简单。只需调用
re.sub()
方法,使用一个正则表达式删除字符串末尾的标点符号-与编写的完全相同。
>>> 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'