PDA

View Full Version : Python: seperate string




lynkynpark86
Dec 7, 2011, 06:40 AM
So I have a program that generates 2 ints separated by a space (eg '5 93' or '34 115'). I need to set the first to one int, and the second to another. I have no idea how large the numbers would be ('21478 61247' is a possibility, so is '6 3'). How would I do this?



subsonix
Dec 7, 2011, 07:13 AM
You could try something like this, the fields will be separated into two array indexes and then converted to ints.


>>> numbers = "123 456"
>>> array = numbers.split(' ')
>>> int1 = int(array[0])
>>> int2 = int(array[1])
>>> int1
123
>>> int2
456


You can re-assign the int values to array[0] and array[1] rather than to two new variables if you want to. Don't know what the limit of int is in python, you might have to use long ints instead.

lynkynpark86
Dec 7, 2011, 07:19 AM
You could try something like this, the fields will be separated into two array indexes and then converted to ints.


>>> numbers = "123 456"
>>> array = numbers.split(' ')
>>> int1 = int(array[0])
>>> int2 = int(array[1])
>>> int1
123
>>> int2
456


You can re-assign the int values to array[0] and array[1] rather than to two new variables if you want to. Don't know what the limit of int is in python, you might have to use long ints instead.

Thanks, I knew I could use split, but I didn't understand the concept at all.