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
Post a Comment