19

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.

oscilatorium
  • 307
  • 1
  • 2
  • 4

1 Answers1

23

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

Just do:

    <!-- language: python -->
    strTup = '(5,6)'
    eval(strTup)
Jean-François Fabre
  • 137,073
  • 23
  • 153
  • 219
Luna Feng
  • 395
  • 1
  • 5
  • 18
    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`. – crypdick Sep 20 '19 at 23:32
  • 1
    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. – Muneeb Ahmad Khurram Mar 10 '23 at 14:14