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

后端 未结 5 1471
礼貌的吻别
礼貌的吻别 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:38

    split will always return a list. a, b = ... will always expect list length to be two. You can use something like l = string.split(':'); a = l[0]; ....

    Here is a one liner: a, b = (string.split(':') + [None]*2)[:2]

提交回复
热议问题