Home > Backend Development > Python Tutorial > How to convert str to int in python

How to convert str to int in python

WBOY
Release: 2024-03-01 16:31:25
forward
631 people have browsed it

How to convert str to int in python

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 &#x27;int&#x27;>
Copy after login

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
Copy after login

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!

Related labels:
source:lsjlt.com
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template