Python Convert String to Integer

Document 对象参考手册Python3 Examples

In Python, we can use the built-inint()The function converts a string to an integer. This function attempts to parse the string as an integer and returns the corresponding integer value. If the string cannot be parsed as an integer, it will throwValueErroran 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 explanation:

  • str_num = "123": Define a string variablestr_num, whose value is"123"。
  • int_num = int(str_num): Useint()The function converts the stringstr_numto an integer, and assigns the result to the variableint_num。
  • print(int_num): Print the converted integer.

Output:

123

If the string contains non-numeric characters, for example"123abc", thenint()the function will throwValueErroran exception.

Document 对象参考手册Python3 Examples

Other Extensions