[Tutor] Splitting lists with strings and integers

Sam Lalonde sl70176 at gmail.com
Tue Nov 26 20:00:41 CET 2013


Hi, I am very new to python.

I have a list with mixed strings/integers.  I want to convert this to a
list of lists, and I want the numbers to get stored as integers.

>>> list1 = ['dog 1 2', 'cat 3 4', 'mouse 5 6']
>>> list2 = []
>>> for animal in list1:
...     animal = animal.split()
...     list2.append(animal)
...
>>> print list2
[['dog', '1', '2'], ['cat', '3', '4'], ['mouse', '5', '6']]
>>>
>>> for animal in list2:
...     print animal[1] + animal[2]
...
12
34
56

You can see that it just appended the numbers to each other.  I'd like the
output to be:

3
7
11

Is there a clean way to get the numbers stored as int instead of str when I
build list2?

Thanks
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <http://mail.python.org/pipermail/tutor/attachments/20131126/18c2d2c4/attachment-0001.html>


More information about the Tutor mailing list