To convert a string to an integer, use the built-in
int() function. The
function takes a string as input and returns an integer as its output.
Here's an example of using
>>> string = "123" >>> int(string) 123
You need to convert a string to an int before you can use it to calculate things. In other words, changing the type of a variable can affect the behavior when using that variable.
As an example, consider the difference between the two uses of
+ in this
>>> "123" + "456" '123456' >>> int("123") + int("456") 579
Some strings do not represent valid numbers. If you try to convert such a string, you will get an exception:
>>> int("not a number") Traceback (most recent call last): File "<stdin>", line 1, in <module> ValueError: invalid literal for int() with base 10: 'not a number'
To handle such cases, use a
try: number = int(some_variable) except ValueError: print("some_variable did not contain a number!")
Sometimes your number has a dot in it. In this case, you might want to use
float() instead of
int(); otherwise you will get an error:
>>> text = "123.456" >>> int(text) Traceback (most recent call last): File "<stdin>", line 1, in <module> ValueError: invalid literal for int() with base 10: '123.456' >>> float(text) 123.456
If your string uses a different base, you can specify the base as a second
int(). For example:
>>> int("0x123", 16) 291
The fastest way to learn programming is with lots of practice. Learn a programming concept, then write code to test your understanding and make it stick. Try our online interactive Python course today—it's free!