Using regex to add leading zeroes

后端 未结 11 1147
长情又很酷
长情又很酷 2020-12-05 13:07

I would like to add a certain number of leading zeroes (say up to 3) to all numbers of a string. For example:

Input: /2009/5/song 01 of 12

Outpu

11条回答
  •  无人及你
    2020-12-05 13:51

    Use something that supports a callback so you can process the match:

    >>> r=re.compile(r'(?:^|(?<=[^0-9]))([0-9]{1,3})(?=$|[^0-9])')
    >>> r.sub(lambda x: '%04d' % (int(x.group(1)),), 'dfbg345gf345', sys.maxint)
    'dfbg0345gf0345'
    >>> r.sub(lambda x: '%04d' % (int(x.group(1)),), '1x11x111x', sys.maxint)
    '0001x0011x0111x'
    >>> r.sub(lambda x: '%04d' % (int(x.group(1)),), 'x1x11x111x', sys.maxint)
    'x0001x0011x0111x'
    

提交回复
热议问题