How to convert strings into integers? How to convert strings into integers? python python

# How to convert strings into integers?

`int()` is the Python standard built-in function to convert a string into an integer value. You call it with a string containing a number as the argument, and it returns the number converted to an integer:

``>>> int("1") + 12``

If you know the structure of your list, T1 (that it simply contains lists, only one level), you could do this in Python 3:

``T2 = [list(map(int, x)) for x in T1]``

In Python 2:

``T2 = [map(int, x) for x in T1]``

You can do this with a list comprehension:

``T2 = [[int(column) for column in row] for row in T1]``

The inner list comprehension (`[int(column) for column in row]`) builds a `list` of `int`s from a sequence of `int`-able objects, like decimal strings, in `row`. The outer list comprehension (`[... for row in T1])`) builds a list of the results of the inner list comprehension applied to each item in `T1`.

The code snippet will fail if any of the rows contain objects that can't be converted by `int`. You'll need a smarter function if you want to process rows containing non-decimal strings.

If you know the structure of the rows, you can replace the inner list comprehension with a call to a function of the row. Eg.

``T2 = [parse_a_row_of_T1(row) for row in T1]``

I would rather prefer using only comprehension lists:

``[[int(y) for y in x] for x in T1]``