-1

If I have data like this from a machine learning prediction:

print(prediction) is:

('blood_pressure', '0.99999046')

Then print(type(prediction)) is:

<class 'str'>

How do I convert this to a tuple?

If i do print(tuple(prediction)) this comes out like:

('(', "'", 'b', 'l', 'o', 'o', 'd', '_', 'p', 'r', 'e', 's', 's', 'u', 'r', 'e', "'", ',', ' ', "'", '0', '.', '9', '9', '9', '9', '9', '0', '4', '6', "'", ')')
bbartling
  • 3,288
  • 9
  • 43
  • 88

2 Answers2

0

You can use the builtin eval() function.

tuple_as_string = "('blood_pressure', '0.99999046')"
tuple_as_tuple = eval(tuple_as_string)
print(tuple_as_tuple)
print(type(tuple_as_tuple))
S P Sharan
  • 1,101
  • 9
  • 18
0

If you don't want to use eval, as it is inherently unsecure this is also possible, even though not as elegant:

s = "('blood_pressure', '0.99999046')"
s.replace("(","").replace(")","").replace("'","").split(",")
['blood_pressure', ' 0.99999046']
FloLie
  • 1,820
  • 1
  • 7
  • 19
  • I know this is an old comment, but just as a shortcut, you could use `s.strip("()'")` instead of the multiple calls to `replace`. – hyit Jun 06 '23 at 11:48