1

how can I convert a string to an int in python say I have this array

['(111,11,12)','(12,34,56)'] to [(111,11,12),(12,34,56)]

Any help will be appreciated thanks

miik
  • 663
  • 1
  • 8
  • 23
  • @closevoter: I don't see any reason why this should be too localized though you may choose to vote it as a duplicate – Abhijit Dec 27 '12 at 14:52

5 Answers5

8
import ast
a = "['(111,11,12)','(12,34,56)']"
[ast.literal_eval(b) for b in ast.literal_eval(a)]
# [(111, 11, 12), (12, 34, 56)]

EDIT: if you have a list of strings (and not a string), just like @DSM suggests, then you have to modify it:

a = ['(111,11,12)','(12,34,56)']
[ast.literal_eval(b) for b in a]
# [(111, 11, 12), (12, 34, 56)]
eumiro
  • 207,213
  • 34
  • 299
  • 261
  • 1
    The OP seems to have a list of strings, not a string (the modification is trivial, of course.) – DSM Dec 27 '12 at 17:12
  • 2
    @Goranek `ast.literal_eval` is different from the built-in `eval` - it is completely safe to use even when dealing with data from untrusted sources. See http://docs.python.org/2/library/ast.html#ast-helpers for more info. – RocketDonkey Dec 30 '12 at 16:52
0

You could try some re:

import re
src = ['(111,11,12)', '(12,34,56)']
[tuple([int(n) for n in re.findall(r"(\d+),(\d+),(\d+)", s)[0]]) for s in src]
petrs
  • 405
  • 5
  • 10
0

By reading your question I see you have a list of strings:

l = ['(111,11,12)','(12,34,56)']

and you want to convert that to a list of numbers...

# some cleaning first
number_list = [x.strip('()').split(',') for x in l]
for numbers in number_list:
    numbers[:] = [int(x) for x in numbers]
print number_list

Sorry for that list comprehension parsing, if you're new that looks weird but is a very common python idiom and you should get familiar with it.

MGP
  • 2,981
  • 35
  • 34
0

Have fun!

def customIntparser(n):
    exec("n="+str(n))
    if type(n) is list or type(n) is tuple:
        temps=[]
        for a in n:
            temps.append(customIntparser(str(a)))
        if type(n) is tuple:
            temps=tuple(temps)
        return temps
    else:
        exec("z="+str(n))
        return z

Sample tests:

>>>s = "['(111,11,12)','(12,34,56)']"
>>>a=customIntparser(s)
>>> a
# [(111, 11, 12), (12, 34, 56)]
>a[0][1]
# 11
sadaf2605
  • 7,332
  • 8
  • 60
  • 103
-2

You can convert a string to an int with the int() keyword:

Python 2.7.2 (default, Jun 20 2012, 16:23:33) 
[GCC 4.2.1 Compatible Apple Clang 4.0 (tags/Apple/clang-418.0.60)] on darwin
Type "help", "copyright", "credits" or "license" for more information.
>>> int('42')
42

But the example you give seems to indicate that you want to do this for an entire tuple, not a single integer. If so, you can use the builtin eval function:

>>> eval('(111,111)')
(111, 111)
  • -1: Your answer is least helpful to the OP's question and please don't suggest the dreaded eval. – Abhijit Dec 27 '12 at 14:54