Stop A Loop When A Value Is Found And Then Add Values To A List
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?
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
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
- → What are the pluses/minuses of different ways to configure GPIOs on the Beaglebone Black?
- → Django, code inside <script> tag doesn't work in a template
- → React - Django webpack config with dynamic 'output'
- → GAE Python app - Does URL matter for SEO?
- → Put a Rendered Django Template in Json along with some other items
- → session disappears when request is sent from fetch
- → Python Shopify API output formatted datetime string in django template
- → Shopify app: adding a new shipping address via webhook
- → Shopify + Python library: how to create new shipping address
- → shopify python api: how do add new assets to published theme?
- → Access 'HTTP_X_SHOPIFY_SHOP_API_CALL_LIMIT' with Python Shopify Module