How can i make a loop that eliminates zeroes from a list of strings that looks something like this:
List
GR0030
GR00000000013
GR093
I’d like to eliminate the zeroes between the GR and the first number different than zero. I’ve thought with something like this:
entry = ""
for x in list:
if x.isalpha():
entry = entry + x
else:
if x == 0:
entry = entry
else:
entry = entry + x[(list.index(x)):-1]
break
list1.append(entry) # the answer list
But it does not work, I’m just getting a list full of GR in each row. What I’m doing wrong?
Thanks for your answer
>Solution :
A regular expression will do here. The expression matches the first group of zeroes, and replaces them with an empty string. To prevent us from reading past the first group, we set count=1.
Your approach could work, but you’d have to keep track of whether or not you’ve seen a zero before. You also should try to avoid repeated concatenation of strings, as it isn’t very efficient.
import re
def strip_intermediate_zeroes(s):
return re.sub('0+', '', s, count=1)
items = ['GR0030', 'GR00000000013', 'GR093']
print(list(map(strip_intermediate_zeroes, items)))
This answer assumes that there’s at least one zero after "GR". If such an assumption cannot be made, you can explicitly check for that as a quick fix:
def strip_intermediate_zeroes(s):
if s.startswith('GR0'):
return re.sub('0+', '', s, count=1)
return s