Search code examples
pythonstringstrip

Why does Python's rstrip remove more characters than expected?


According to the docs the function will strip that sequence of chars from the right side of the string.
The expression 'https://odinultra.ai/api'.rstrip('/api') should result in the string 'https://odinultra.ai'.

Instead here is what we get in Python 3:

>>> 'https://odinultra.ai/api'.rstrip('/api')
'https://odinultra.'

Solution

  • rstrip('/api') won't remove the suffix /api, but a sequence made up of any of the characters /, a, p or i from the end of the string. This isn't a bug, but the documented behavior:

    The chars argument is not a suffix; rather, all combinations of its values are stripped

    For your usecase, you should use removesuffix instead:

    'https://odinultra.ai/api'.removesuffix('/api')