安卓系统

如何在python中将字符串转换为整数

Python3变量的基本运算与互相转换 #15 Integer, Float, String, and Boolean in Python3

Python3变量的基本运算与互相转换 #15 Integer, Float, String, and Boolean in Python3

目录:

Anonim

Python中的所有数据类型(包括整数和字符串)都是对象。 通常在编写Python代码时,您需要将一种数据类型转换为另一种数据类型。 例如,要对表示为字符串的数字进行数学运算,需要将其转换为整数。

在本教程中,我们将向您展示如何将Python字符串转换为整数。

Python int() 函数

内置的 int() 函数从给定的数字或字符串返回一个十进制整数对象。 它采用以下形式:

int(x, base=10)

函数接受两个参数:

  • x 要转换为整数的字符串或数字。 base 它代表第一个参数的数字系统。 它的值可以是0和2–36。 如果没有给出基数,则默认值为10(十进制整数)。

通常,整数以十六进制(基数16),十进制(基数10),八进制(基数8)或二进制(基数2)表示。

如果给定参数不能表示为整数,则该函数将引发 ValueError 异常。

将Python字符串转换为整数

在Python中,“字符串”是使用单引号( ' ),双引号( """ )或三引号( """ )声明的字符列表。

如果使用引号声明仅包含数字的变量,则其数据类型将设置为String。 考虑以下示例:

days = "23" type(days)

type() 函数向我们显示 days 是一个String对象。

让我们尝试对变量进行数学运算:

print(days+5)

Python将抛出 TypeError 异常错误,因为我们无法使用字符串和整数执行加法计算:

Traceback (most recent call last): File " ", line 1, in TypeError: cannot concatenate 'str' and 'int' objects Traceback (most recent call last): File " ", line 1, in TypeError: cannot concatenate 'str' and 'int' objects Traceback (most recent call last): File " ", line 1, in TypeError: cannot concatenate 'str' and 'int' objects

要将十进制整数的字符串表示形式转换为 int ,请将字符串传递给 int() 函数,该函数返回一个十进制整数:

days = "23" days_int = int(days) type(days_int)

print(days_int+5)

28

如果数字包含逗号(标记成千上万,数百万等),则需要先删除逗号,然后再将数字传递给 int() 函数:

total = "1, 000, 000" int(total.replace(", ", ""))

1000000

在不同数字系统中转换表示整数的字符串时,请确保使用正确的 base

例如,在十六进制系统中,数字54732表示为 D5CF 。 要将其转换为十进制整数,您需要使用基数16:

int("D5CF", 16)

54735

如果将 D5CF 字符串传递给 int() 函数而不设置基数,则它将引发 ValueError 异常:

int("D5CF")

Traceback (most recent call last): File " ", line 1, in ValueError: invalid literal for int() with base 10: 'D5CF' Traceback (most recent call last): File " ", line 1, in ValueError: invalid literal for int() with base 10: 'D5CF' Traceback (most recent call last): File " ", line 1, in ValueError: invalid literal for int() with base 10: 'D5CF'

结论

在Python中,您可以使用 int() 函数将字符串转换为整数。

蟒蛇