Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
131 views
in Technique[技术] by (71.8m points)

python - Splitting numbers from letters

I have a column that contains values such as:

7D  
13M  
24D  
55D  

I want to split the values into a group of the digits and another with the letter so I can further evaluate.

I am pretty close using the built in regex with this function

def string_split(type: str):
  res = re.findall(('d+'), type)
  
  if ["d"] in res:
    return "days"
  if ["m"] in res:
    return "months"

right now my re.findall is only returning the digits and not the letters.

question from:https://stackoverflow.com/questions/65837729/splitting-numbers-from-letters

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

Don't use re.findall(). Your strings are always a number followed by a letter. So use a regular expression that matches just that pattern, rather than splitting it.

def string_split(type: str):
    m = re.match('(d+)([A-Z])', type)
    if m:
        num = m.group(1)
        unit = m.group(2)
        if unit == 'D':
            return num, 'days'
        elif unit == 'M':
            return num, 'months'
        else:
            raise ValueError('Invalid unit ' + unit)
    else:
        raise ValueError('Invalid interval ' + type)

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...