How do I convert a string to a number?
For integers, use the built-in int type constructor, e.g. int(‘144’) == 144. Similarly, float converts to floating-point, e.g. float(‘144’) == 144.0.
By default, these interpret the number as decimal, so that int(‘0144’) == 144 and int(‘0x144’) raises ValueError. int(string, base) takes the base to convert from as a second optional argument, so int(‘144’, 16) == 324. If the base is specified as 0, the number is interpreted using Python’s rules: a leading ‘0’ indicates octal, and ‘0x’ indicates a hex number.
Do not use the built-in function eval if all you need is to convert strings to numbers. eval will be significantly slower and it presents a security risk: someone could pass you a Python expression that might have unwanted side effects. For example, someone could pass __import__(‘os’).system(“rm -rf $HOME”) which would erase your home directory.
CATEGORY: programming
Comment:
Since with conversion you often also want to validate, you may want to look at the FormEncode library (http://formencode.org/). This allows you to check values to be converted against different validators and take appropriate actions, if they don't match (e.g. supply a default value). Most common validators are already included, e.g. numbers, strings, emails addresses, dates, etc., but you can also write custom valiadators and apply a bundle of validators to a whole data structure at once.
Posted by Christopher Arndt (2006-11-15)