python函数返回第一个非零条带中间零并返回数字字符串的最后一部分

zig*_*ggy 2 python

给定一个像'0104002'这样的短信字符串,我需要一个回报01 4002.

当数字大于0时,基本上返回数字文本字符串的第一部分.然后对于第二部分,返回以下一个非零数字开头的部分,直到字符串结尾.每个输入的数字位置会有所不同,字符串的长度也不一样

到目前为止,我只能得到我需要的第一部分

def lot(num):
    lot=""
    for x in num:
        lot+=x
        y=int(x)
        if y>0: break
    print lot

lot('0104002')
Run Code Online (Sandbox Code Playgroud)

use*_*471 5

对于正则表达式来说,这似乎是微不足道的:

>>> import re
>>> re.match(r'^(0*[^0]+)0+([^0].*)$', '0104002').groups()
('01', '4002')
Run Code Online (Sandbox Code Playgroud)

此正则表达式定义了两个由一个或多个零分割的组.拆分由第一系列零点定义,出现在第一个非零序列之后.分裂之前的内容属于第一组,之后的内容属于第二组.

对于任何发现正则表达式令人生畏的人,这里是"详细"解释版本.

re.match(
    r'''^
        (        # Begin first group
          0*     # Allow for some number of leading zeroes
          [^0]+  # Match a series of non-zeroes
        )        # End first group
        0+       # Match some series of zeroes (the separator)
        (        # Begin second group
          [^0]   # Match the first non-zero character
          .*     # Match anything afterward
        )        # End second group
        $
    ''',
    '0104002',
    flags=re.VERBOSE).groups()
Run Code Online (Sandbox Code Playgroud)