I have several alphanumeric strings like these
listOfNum = ['000231512-n','1209123100000-n00000','alphanumeric0000', '000alphanumeric']
The desired output for removing trailing zeros would be:
listOfNum = ['000231512-n','1209123100000-n','alphanumeric', '000alphanumeric']
The desired output for leading trailing zeros would be:
listOfNum = ['231512-n','1209123100000-n00000','alphanumeric0000', 'alphanumeric']
The desire output for removing both leading and trailing zeros would be:
listOfNum = ['231512-n','1209123100000-n00000','alphanumeric0000', 'alphanumeric']
For now i've been doing it the following way, please suggest a better way if there is:
listOfNum = ['000231512-n','1209123100000-n00000','alphanumeric0000', \
'000alphanumeric']
trailingremoved = []
leadingremoved = []
bothremoved = []
# Remove trailing
for i in listOfNum:
while i[-1] == "0":
i = i[:-1]
trailingremoved.append(i)
# Remove leading
for i in listOfNum:
while i[0] == "0":
i = i[1:]
leadingremoved.append(i)
# Remove both
for i in listOfNum:
while i[0] == "0":
i = i[1:]
while i[-1] == "0":
i = i[:-1]
bothremoved.append(i)
You can simply do this with a bool:
Did you try with strip() :
Remove leading + trailing '0':
Remove leading '0':
Remove trailing '0':
str.strip
is the best approach for this situation, butmore_itertools.strip
is also a general solution that strips both leading and trailing elements from an iterable:Code
Details
Notice, here we strip both leading and trailing
"0"
s among other elements that satisfy a predicate. This tool is not limited to strings.See also docs for more examples of
more_itertools.strip
: strip both endsmore_itertools.lstrip
: strip the left endmore_itertools.rstrip
: strip the right endmore_itertools
is a third-party library installable via> pip install more_itertools
.What about a basic
to remove both trailing and leading zeros ? If you're only interested in removing trailing zeros, use
.rstrip
instead (and.lstrip
for only the leading ones).[More info in the doc.]
You could use some list comprehension to get the sequences you want like so: