格式化一个字符串,其中变量并不总是存在于Python中

时间:2013-11-22 23:53:12

标签: python regex parsing formatting

在我的一个项目中,我正在尝试解析有时会发生的地块编号,有时候没有很多扩展(最后是三位数代码)。我显然可以创建一个if elif结构来处理不存在批量扩展的情况,但我希望能够满足我的好奇心并获得一些关于编写代码的更有效方法的反馈。

在目前的状态下,我最终在包裹上留下了一个不需要的尾随破折号而没有很多扩展名:'00 -000-0000 - '

最终地块编号格式应为:

  • 00-000-0000
  • 00-000-0000-000

,输入引脚如下:

pin_that_wont_work1 = '00000000'
pin_that_wont_work2 = '000000000'
pin_that_works1 =     '00000000000'
pin_that_works2 =     '000000000000'

import re

pattern = r'^(\d{1,2})(\d{3})(\d{4})(\d{3})?$'

def parse_pins(pattern, pin):
    L = [x for x in re.search(pattern, pin).groups()]
    return '{dist}-{map_sheet}-{lot}-{lot_ext}'.format(dist=L[0] if len(L[0]) == 2 else '0'+L[0],
                                                       map_sheet=L[1],
                                                       lot=L[2],
                                                       lot_ext=L[3] if L[3] else '')

3 个答案:

答案 0 :(得分:2)

也许我错过了什么,但你不能把短信放在格式调用中吗?

def parse_pins(pattern, pin):
    L = [x for x in re.search(pattern, pin).groups()]
    return '{dist}-{map_sheet}-{lot}{lot_ext}'.format(dist=L[0] if len(L[0]) == 2 else '0'+L[0],
                                                       map_sheet=L[1],
                                                       lot=L[2],
                                                       lot_ext='-{0}'.format(L[3]) if L[3] else '')

答案 1 :(得分:2)

将它们放在列表中,并列出list_.join(' - ')。该列表应具有3或4个值。

答案 2 :(得分:2)

import re

pin_pattern = re.compile(r'^(\d{1,2})(\d{3})(\d{4})(\d{3})?$')

pin_formats = {
    3: '{0:02d}-{1:03d}-{2:04d}',
    4: '{0:02d}-{1:03d}-{2:04d}-{3:03d}'
}

def parse_pin(s):
    groups = [int(d) for d in pin_pattern.search(s).groups() if d is not None]
    return pin_formats[len(groups)].format(*groups)