Python - Splitting numbers and letters into sub-strings with regular expression

前端 未结 2 1730
不知归路
不知归路 2021-01-25 09:59

I am creating a metric measurement converter. The user is expected to enter in an expression such as 125km (a number followed by a unit abbreviation). For conversio

相关标签:
2条回答
  • What's wrong with re.findall ?

    >>> s = '125km'
    >>> re.findall(r'[A-Za-z]+|\d+', s)
    ['125', 'km']
    

    [A-Za-z]+ matches one or more alphabets. | or \d+ one or more digits.

    OR

    Use list comprehension.

    >>> [i for i in re.split(r'([A-Za-z]+)', s) if i]
    ['125', 'km']
    >>> [i for i in re.split(r'(\d+)', s) if i]
    ['125', 'km']
    
    0 讨论(0)
  • 2021-01-25 10:35

    Split a string into list of sub-string (number and others)

    Using program:

    s = "125km1234string"
    sub = []
    char = ""
    num = ""
    for letter in s:
        if letter.isdigit():
            if char:
                sub.append(char)
                char = ""
            num += letter
        else:
            if num:
                sub.append(num)
                num = ""
            char += letter
    sub.append(char) if char else sub.append(num)
    print(sub)
    

    Output

    ['125', 'km', '1234', 'string']
    
    0 讨论(0)
提交回复
热议问题