Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to convert strings into integers?

I have a tuple of tuples from a MySQL query like this:

T1 = (('13', '17', '18', '21', '32'),       ('07', '11', '13', '14', '28'),       ('01', '05', '06', '08', '15', '16')) 

I'd like to convert all the string elements into integers and put them back into a list of lists:

T2 = [[13, 17, 18, 21, 32], [7, 11, 13, 14, 28], [1, 5, 6, 8, 15, 16]] 

I tried to achieve it with eval but didn't get any decent result yet.

like image 231
elfuego1 Avatar asked Mar 13 '09 10:03

elfuego1


People also ask

Can you turn strings into integers?

We can convert String to an int in java using Integer. parseInt() method. To convert String into Integer, we can use Integer. valueOf() method which returns instance of Integer class.

How do you convert a string into an integer in Python?

To convert, or cast, a string to an integer in Python, you use the int() built-in function. The function takes in as a parameter the initial string you want to convert, and returns the integer equivalent of the value you passed. The general syntax looks something like this: int("str") .

How do I print a string as an integer?

To convert a string to integer in Python, use the int() function. This function takes two parameters: the initial string and the optional base to represent the data. Use the syntax print(int("STR")) to return the str as an int , or integer.

Which function converts a string value to a integer?

The atoi() function converts a character string to an integer value. The input string is a sequence of characters that can be interpreted as a numeric value of the specified return type. The function stops reading the input string at the first character that it cannot recognize as part of a number.


1 Answers

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") + 1 2 

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] 
like image 95
unwind Avatar answered Sep 16 '22 17:09

unwind