Python Regular Expression; replacing a portion of match

前端 未结 4 1258
时光说笑
时光说笑 2020-12-22 00:04

How would I limit match/replacement the leading zeros in e004_n07? However, if either term contains all zeros, then I need to retain one zero in the term (see example below

4条回答
  •  梦毁少年i
    2020-12-22 01:02

    If your requirement is that you MUST use regex, then below is your regex pattern:

    >>> import re
    >>> s = 'e004_n07'
    >>> line = re.sub(r"0", "", s)
    >>> line
    'e4_n7'
    

    However it is recommended not to use regex when there is other efficient way to perform the same opertaion, i.e. using replace function

    >>> line = s.replace('0', '')
    >>> line
    'e4_n7'
    

提交回复
热议问题