Piefon eddykashun

I have a function that works just fine. It takes a string and returns an array containing just the groups of digits as strings. For example if you pass :

BA12345-67-089-45fr5sdd3

you will get this returned :

[‘12345’,‘67’,‘089’,‘45’,‘5’,‘3’]

Doesn’t work with negatives or decimal points, but for me it doesn’t have to. My issue is that it just looks long winded, and wondered if someone more adept with python could improve on it. Here is the function :

def my_split2(line):
  current_str = None
  result=[]
  for ch in line:
    if ch.isdigit():
      if current_str is None:
        current_str = str(ch)
      else:
        current_str += str(ch)
    else:
      if current_str is not None:
        result.append(current_str)
        current_str = None
        
  # Add any stragglers.
  if current_str is not None:
    result.append(current_str)
    
  return result

Now, I know I can also do this (found it on SO I think) :

result = ["".join(x) for is_number, x in itertools.groupby(line, key=str.isdigit) if is_number is True]

but I can’t import itertools on the client and this needs to be client side.

This whole exercise is purely to improve my Python.

And as soon as I post, I find this :

import re
...
str1="12345-67-89"
print (re.findall('\d+', str1 ))

which seems to do exactly the same thing.

2 Likes