python - Automatically convert string to the right numerical type -


i wondering if there's elegant , easy way convert string (that know can converted number) corresponding numerical type. example, if string represents integer, want value converted int; same long, float, , on.

you use ast.literal_eval.

import ast  examples = ["1", "1.5", "999999999999999999999999999999999999999999", "23+42j"] item in examples:     result = ast.literal_eval(item)     print result     print type(result) 

result:

1 <type 'int'> 1.5 <type 'float'> 999999999999999999999999999999999999999999 <type 'long'> (23+42j) <type 'complex'> 

Comments

Popular posts from this blog

java - Custom OutputStreamAppender not run: LOGBACK: No context given for <MYAPPENDER> -

java - UML - How would you draw a try catch in a sequence diagram? -

c++ - No viable overloaded operator for references a map -