1
k = '9\t10\t12314\t12\t13\t14\t'
print(k.rstrip('\t12\t13\t14\t'))

For this given code the output that I would've expected is:

9 10 12314

But the output that I obtain on running this code is:

9 10

Replacing 12314 with any sequence of integers from 1-4 leads to this same faulty output, but the moment it reaches an integer greater than 5 it stops stripping the string. For example if we added a 5 in between 12314:

k = '9\t10\t123514\t12\t13\t14\t'
print(k.rstrip('12\t13\t14\t'))

Leads to the output:

9 10 1235

An explanation of why this happens would be appreciated. I tried looking up the code for the rstrip() function but I didn't find anything useful, but that might just be because I don't dig through source code too often. Also, I have been able to recreate this in python 3.x as well as 2.x so as far as I know it isn't version-specific.

Adam Jijo
  • 82
  • 1
  • 7

2 Answers2

2

It's because strip function in Python try to strip every "character(s)" passed into the function.

For example:

> 'test1234'.rstrip('4')
test123                       # expected

> 'test1234'.rstrip('34')
test12                        # expected

> 'test1234'.rstrip('43')
test12                        # try to strip every `4` and `3`

Example: https://www.w3schools.com/python/trypython.asp?filename=demo_ref_string_rstrip2


I think what you need is removesuffix which is available on Python 3.9 or above :)

> 'test1234'.removesuffix('34')
test12

> 'test1234'.removesuffix('43')
test12      # do nothing since string does not ends with `43`

See more about removesuffix here.

But if you cannot go to Python 3.9 then this might help :)

Preeti Y.
  • 429
  • 4
  • 11
1

I think you think .strip() is doing something different then it actually does.

.strip() and .rstrip() remove all characters on of the iterable you provide. This means:

"all my allmonds".strip("my all")

will leave only "onds" because strip will strip the following: " ", "a", "l", "m", "y" and !not! "my all" as you might have expected.

As for an solution, you can use regex.

Andreas
  • 8,694
  • 3
  • 14
  • 38