1

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?

BrokenBenchmark
  • 18,126
  • 7
  • 21
  • 33
Juank
  • 55
  • 7

2 Answers2

1

This seems like a natural fit for a regex combined with re.sub(). (?<=^GR)0* means 0 or more zeros that follow 'GR' at the beginning of a string.

import re

l = [
    'GR0030',
    'GR00000000013',
    'GR093',
]

rx = re.compile(r'(?<=^GR)0*')
[rx.sub('', s) for s in l]
# ['GR30', 'GR13', 'GR93']

This is very specific in that it won't change strings like 'SP0091', 'ADGR0000400013', or '000ab'.

Mark
  • 90,562
  • 7
  • 108
  • 148
1

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
BrokenBenchmark
  • 18,126
  • 7
  • 21
  • 33