In Perl I can do:
my ($x, $y) = split /:/, $str;
And it will work whether or not the string contains the pattern.
In Python, however this won't work:
a, b = "foo".split(":") # ValueError: not enough values to unpack
What's the canonical way to prevent errors in such cases?
The split() method splits a string into a list. You can specify the separator, default separator is any whitespace. Note: When maxsplit is specified, the list will contain the specified number of elements plus one.
You can split a string using the newline character (\n) in Python. We will take a string which will be separated by the newline character and then split the string. The newline character will act as the separator in the Split function.
Note: The split() method does not change the original string. Remember – JavaScript strings are immutable. The split method divides a string into a set of substrings, maintaining the substrings in the same order in which they appear in the original string. The method returns the substrings in the form of an array.
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
.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With