Ad

Stop A Loop When A Value Is Found And Then Add Values To A List

- 1 answer

How can I make a loop that eliminates zeroes from a list of strings that looks something like the following?

List
GR0030
GR00000000013
GR093

I'd like to eliminate the zeroes between the GR and the first number different than zero. I've thought I could solve this problem 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 am I doing wrong?

Ad

Answer

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)))

The above code snippet assumes that there's at least one zero after "GR". If such an assumption cannot be made, you can explicitly check for that assumption as a quick fix:

def strip_intermediate_zeroes(s):
    if s.startswith('GR0'):
        return re.sub('0+', '', s, count=1)
    return s
Ad
source: stackoverflow.com
Ad