Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Python convert a string to tuple

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

print(prediction) is:

('blood_pressure', '0.99999046')

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

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', "'", ')')

>Solution :

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))
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading