How do I reliably split a string in Python, when it may not contain the pattern, or all n elements?

后端 未结 5 1468
礼貌的吻别
礼貌的吻别 2020-12-04 23:03

In Perl I can do:

my ($x, $y) = split /:/, $str;

And it will work whether or not the string contains the pattern.

In Python, howeve

5条回答
  •  没有蜡笔的小新
    2020-12-04 23:48

    If you're splitting into just two parts (like in your example) you can use str.partition() to get a guaranteed argument unpacking size of 3:

    >>> a, sep, b = 'foo'.partition(':')
    >>> a, sep, b
    ('foo', '', '')
    

    str.partition() always returns a 3-tuple, whether the separator is found or not.

    Another alternative for Python 3.x is to use extended iterable unpacking:

    >>> a, *b = 'foo'.split(':')
    >>> a, b
    ('foo', [])
    

    This assigns the first split item to a and the list of remaining items (if any) to b.

提交回复
热议问题