How to convert a String to an int in Python

Syntax:

int_nb = int(nb)

If the string representation of an object is used for a mathematical formula, Python will return the following error:
TypeError: can only concatenate str (not "int") to str

Example:

nb = "10"
print(nb)

int_nb = int(nb)
print(int_nb)

int_nb2 = int("10")+2

print(int_nb2)

This example creates a variable nb from the String "10". That variable is written in the output. The variable is converted to an integer and written in the output. 10 is written for both calls. Finally the variable int_nb2 is created by converting the String "10" to an int and adding 2. The output is printed to the user.

The output will be:

10
10
12

References:

Python

Recent Comments