Python Convert a String to an Integer
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
(
int_num
)
Code analysis:
str_num = "123": Define a string variablestr_num, whose value is"123"。int_num = int(str_num): When usingint()The function converts the stringstr_numto an integer and assigns the result to the variableint_num。print(int_num): Print the converted integer.
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.
Python3 Examples