How do you translate this regular-expression idiom from Perl into Python?

后端 未结 15 641
情深已故
情深已故 2020-12-04 11:16

I switched from Perl to Python about a year ago and haven\'t looked back. There is only one idiom that I\'ve ever found I can do more easily in Perl than in Python:<

15条回答
  •  眼角桃花
    2020-12-04 11:56

    Alternatively, something not using regular expressions at all:

    prefix, data = var[:3], var[3:]
    if prefix == 'foo':
        # do something with data
    elif prefix == 'bar':
        # do something with data
    elif prefix == 'baz':
        # do something with data
    else:
        # do something with var
    

    Whether that is suitable depends on your actual problem. Don't forget, regular expressions aren't the swiss army knife that they are in Perl; Python has different constructs for doing string manipulation.

提交回复
热议问题