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

How to extract type from string

I need some way to reliably identify whether a string can be of another type eg. "1" would evaluate to 1 – an int, "2.0" would evaluate to 2.0 – a float and "John has 3 apples" would just evaluate to a string. Is there some package that does this – builtin or otherwise?

It would be great if it also worked on dates and currency

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

>Solution :

You can do this with ast.literal_eval

int_type = ast.literal_eval("1")
float_type = ast.literal_eval("2.0")

But will only work on python literal structures: strings, bytes, numbers, tuples, lists, dicts, sets, booleans, None and Ellipsis

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