Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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?

like image 595
planetp Avatar asked Jul 01 '16 15:07

planetp


People also ask

What is the best way to split a string in Python?

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.

How can strings be divided using Python or any other language )? How can it be scaled into a large number of records?

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.

Does split () alter the original string?

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.


1 Answers

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.

like image 167
Eugene Yarmash Avatar answered Sep 21 '22 17:09

Eugene Yarmash