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

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

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

java - Cannot secure connection using TLS -