1

I have a string sentence that contains trailing punctuation that I want to remove. To do this I'm passing a string parameter punctuation to my function remove_punc that contains the trailing punctuation that I want to remove:

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."""

I have tried sentence.rstrip(punctuation) for the example:

remove_punc("This is some, and \"I\" know it is a long one!", "?!.,")

However this returns:

'This is some, and "I" know it is a long one'

The expected output is:

'This is some and "I" know it is a long one'

Am I using rstrip() incorrectly?

Sohaib
  • 23
  • 3
  • 1
    rstrip() works on trailing characters. In your example, the comma that you expect to be removed (after the word 'some') is not a trailing character – cdncat May 31 '21 at 02:06

2 Answers2

0

.rstrip and .strip remove from the beginning and end of a string. They don't effect the middle. For that you should use, .replace or something similar.

Bobby Ocean
  • 3,120
  • 1
  • 8
  • 15
0

lstrip only removes the characters if they're at the beginning (left) of the string, rstrip only removes the characters if they're at the end (right) of the string, while strip is a combination of both lstrip and rstrip. To solve your problem, you'd should look into string.replace() or re.sub().

def remove_punc(sentence, punctuation):
    for punc in punctuation:
        sentence = sentence.replace(punc, '')
    return sentence

or

import re
def remove_punc(sentence, punctuation):
    punctuation = '[' + punctuation + ']'
    return re.sub(punctuation, '', sentence)
Gusti Adli
  • 1,225
  • 4
  • 13