Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
129 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 Reply

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)

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...