Private archive copy · Unofficial site · Content copyright belongs to Runoob Tutorial and the original authors · View Original

Python Convert a String to an Integer

Python Convert a String to an Integer

Document Object Reference Manual Python3 Examples

In Python, we can use the built-in int() function converts a string to an integer. This function tries to parse the string as an integer and returns the corresponding integer value. If the string cannot be parsed as an integer, it raises ValueError exception.

Example

Example string

str_num

=

"123"

Convert the string to an integer

int_num

=

int

(

str_num

)

Print the converted integer

print

(

int_num

)

Code analysis:

Output result:

123

If the string contains non-digit characters, for example "123abc", then int() function raises ValueError exception. Therefore, in real use it is recommended to check whether the string can be converted to an integer first, or to use exception handling to catch possible errors.

Document Object Reference Manual Python3 Examples