21

I have a user entered string which is already in tuple format and would like to convert/cast it to a actual tuple in python. How can I do this? E.g:

strTup = '(5, 6)' 

Would like to convert the above to the tuple (5, 6). I tried tuple(strTup) which did not work as it made each character into its own tuple.

4

1 Answer 1

23

You can pass it to eval() (note: this is unsafe):

Just do:

strTup = '(5,6)' eval(strTup) 
Sign up to request clarification or add additional context in comments.

2 Comments

This is very bad advice!!! A user entered string can arbitrary complex (and potentially malicious) code, and you will just blindly evaluate it on your server! Instead, use ast.literal_eval.
Do note that if you are sure about the data, and the user has no realistic way of generating that data, you can still use eval, using ast.literal_eval is the way to go.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.