In python, you can use the built-in int()
function to convert a string to an integer.
The following is an example:
string = "123" number = int(string) print(number)# 输出:123 print(type(number))# 输出:<class 'int'>
int()
The function can also accept a second parameter, indicating the base of the string. For example, convert a binary string to an integer:
string = "1010" number = int(string, 2) print(number)# 输出:10
In addition to using built-in functions, you can also use other methods for conversion, such as using the eval()
function or using the string method isdi<strong class="keylink">git</strong>()
Judgment If the string contains only numeric characters, then use loops and math operators to build the integer. However, using the int()
function is the most common and recommended method.
The above is the detailed content of How to convert str to int in python. For more information, please follow other related articles on the PHP Chinese website!