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

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

    You are always free to catch the exception.

    For example:

    some_string = "foo"
    
    try:
        a, b = some_string.split(":")
    except ValueError:
        a = some_string
        b = ""
    

    If assigning the whole original string to a and an empty string to b is the desired behaviour, I would probably use str.partition() as eugene y suggests. However, this solution gives you more control over exactly what happens when there is no separator in the string, which might be useful in some cases.

提交回复
热议问题