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
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.