2

Okay, I have this string

tc='(107, 189)'

and I need it to be a tuple, so I can call each number one at a time.

print(tc[0]) #needs to output 107

Thank you in advance!

3 Answers 3

7

All you need is ast.literal_eval:

>>> from ast import literal_eval
>>> tc = '(107, 189)'
>>> tc = literal_eval(tc)
>>> tc
(107, 189)
>>> type(tc)
<class 'tuple'>
>>> tc[0]
107
>>> type(tc[0])
<class 'int'>
>>>

From the docs:

ast.literal_eval(node_or_string)

Safely evaluate an expression node or a Unicode or Latin-1 encoded string containing a Python expression. The string or node provided may only consist of the following Python literal structures: strings, numbers, tuples, lists, dicts, booleans, and None.

Sign up to request clarification or add additional context in comments.

Comments

5

Use ast.literal_eval():

>>> import ast
>>> tc='(107, 189)'
>>> tc_tuple = ast.literal_eval(tc)
>>> tc_tuple
(107, 189)
>>> tc_tuple[0]
107

Comments

0

You can use the builtin eval, which evaluates a Python expression:

>>> tc = '(107, 189)'
>>> tc = eval(tc)
>>> tc
(107, 189)
>>> tc[0]
107

3 Comments

Well, this builtin function exists for a reason, and I think if the OP problem is specific for that kind of expressions, it gets the job done flawlessly and requires no imports.
I'm always confused about why people are against imports. I don't think I've ever written a python script that did not require me to import at least sys or os.
Usually imports are not bad.. but if I can solve a specific problem using the builtins, I'd prefer that. But anyway, note that import (including when importing only few items from the module), actually evaluates the entire module, and maybe, in some rare cases, you may want to avoid that (though, usually it doesn't really matter, and you won't feel any difference).

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.