Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What is the best way to split a variable length string into variables in Python?

Tags:

python

Suppose I have a string of integers separated by commas of variable length. What is the best way to split the string and store the integers into variables?

Currently, I have the following.

input = sys.argv[1]
mylist = [int(x) for x in input.split(',')]
if len(mylist) == 2: a, b = mylist
else: a, b, c = mylist

Is there a more efficient way of doing this?

like image 923
idealistikz Avatar asked Mar 04 '26 18:03

idealistikz


1 Answers

Add sentinels, then limit the list to 3 elements:

a, b, c = (mylist + [None] * 3)[:3]

Now a, b and c are at the very least set to None, and if the number of items is more than three only the first three values are used.

Demo:

>>> mylist = [1, 2]
>>> a, b, c = (mylist + [None] * 3)[:3]
>>> print a, b, c
1 2 None
>>> mylist = [1, 2, 3, 4]
>>> a, b, c = (mylist + [None] * 3)[:3]
>>> print a, b, c
1 2 3

If you need at least 2 elements, use fewer None values and catch ValueError:

try:
    a, b, c = (mylist + [None])[:3]
except ValueError:
    print "You mast specify at least 2 values"
    sys.exit(1)
like image 111
Martijn Pieters Avatar answered Mar 06 '26 06:03

Martijn Pieters



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!