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

ubuntu - How to disable Kernel Module Signing in linux -

java - Ebean enhancement ignores a model -

How to combine associative arrays in bash? -