We're back after a server migration that caused effbot.org to fall over a bit harder than expected. Expect some glitches.

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