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
Answers:
You can use something like str[:-3]
to remove the last the three digits no matter what (using a slice).
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
You can use a regex. For example:
import re
a = "1010101010100000"
a = re.sub('000$', '', a)
print(a)
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]
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
You can use something like str[:-3]
to remove the last the three digits no matter what (using a slice).
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
You can use a regex. For example:
import re
a = "1010101010100000"
a = re.sub('000$', '', a)
print(a)
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]