Python字符串函数rstrip()不工作
我有一个字符串Python字符串函数rstrip()不工作,python,string,Python,String,我有一个字符串句子,其中包含要删除的尾随标点符号。为此,我将向我的函数remove\u punc传递一个字符串参数标点符号,该参数包含我要删除的尾随标点符号: def remove_punc(sentence, punctuation): """takes input parameters sentence (type string) and punctuation (type string), and returns a string that
句子
,其中包含要删除的尾随标点符号。为此,我将向我的函数remove\u punc
传递一个字符串参数标点符号
,该参数包含我要删除的尾随标点符号:
def remove_punc(sentence, punctuation):
"""takes input parameters sentence (type string) and
punctuation (type string), and returns a string that
strips all trailing punctuations in sentence."""
我尝试了句子.rstrip(标点符号)
示例:
remove_punc("This is some, and \"I\" know it is a long one!", "?!.,")
然而,这返回:
'This is some, and "I" know it is a long one'
预期产出为:
'This is some and "I" know it is a long one'
我是否使用了
rstrip()
错误?.rstrip
和.strip
从字符串的开头和结尾删除。它们不会影响中间层。为此,您应该使用,.replace
或类似方法。lstrip
仅删除位于字符串开头(左侧)的字符,rstrip
仅删除位于字符串结尾(右侧)的字符,而strip
是lstrip
和rstrip
的组合。要解决你的问题,你应该研究一下或
或
rstrip()适用于尾随字符。在您的示例中,希望删除的逗号(在单词“some”之后)不是尾随字符
def remove_punc(sentence, punctuation):
for punc in punctuation:
sentence = sentence.replace(punc, '')
return sentence
import re
def remove_punc(sentence, punctuation):
punctuation = '[' + punctuation + ']'
return re.sub(punctuation, '', sentence)