How to remove sequences of "000" from right of a string in Python?

Question:

I am trying to remove sequences of 3 zeros from the right of a string.

I used str.rstrip(‘000’) but it doesn’t work. It just removes all the zeros to the right no matter the amount.

For example 1010101010100000 should become 1010101010100

Asked By: Aleya

||

Answers:

You can use something like str[:-3] to remove the last the three digits no matter what (using a slice).

Answered By: The Peeps191

You can just rely on regular expressions, and write e.g.:

import re

s = '1010101010100000000'

res = re.sub(r'(000)*$', '', s)
# remove trailing zeroes if there are 3⋅n of these
# (you should just remove the '*' if you want n=1)

print(res)
# → 1010101010100
Answered By: ErikMD

You can use a regex. For example:

import re

a = "1010101010100000"

a = re.sub('000$', '', a)

print(a)
Answered By: Amit Eyal

To alter the string from right to left, we can simply reverse the string, replace all occurrences of "000" and reverse it back to it’s original state.

s = s[::-1].replace("000", "")[::-1]
Answered By: excepts
Categories: questions Tags:
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.