13

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
  • 147
  • 1
  • 1
  • 4

1 Answers1

16

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

Just do:

    <!-- language: python -->
    strTup = '(5,6)'
    eval(strTup)
Jean-François Fabre
  • 131,796
  • 23
  • 122
  • 195
Luna Feng
  • 325
  • 1
  • 5
  • 10
    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