PHP前端开发

如何在Python中将字符串转换为数字?

百变鹏仔 1个月前 (01-20) #Python
文章标签 转换为

要将字符串转换为数字,有多种方法。让我们一一看看。

使用 int() 将字符串转换为数字

示例

在此示例中,我们将使用 int() 方法将字符串转换为数字 -

# String to be convertedmyStr = "200"# Display the string and it's typeprint("String = ",myStr)print("Type= ", type(myStr))# Convert the string to integer using int() and display the typemyInt = int(myStr)print("Integer = ", myInt)print("Type = ", type(myInt))

输出

String =  200Type=  <class>Integer =  200Type =  <class></class></class>

使用 float() 将字符串转换为数字

示例

在此示例中,我们将使用 float() 方法将字符串转换为浮点数,然后使用 int() 方法将浮点数转换为整数 -

# String to be convertedmyStr = "500"# Display the string and it's typeprint("String = ",myStr)print("Type= ", type(myStr))# Convert the string to floatmyFloat = float(myStr)print("Float = ", myFloat)print("Type = ", type(myFloat))# Convert the float to intmyInt = int(myFloat)print("Integer = ", myInt)print("Type = ", type(myInt))

输出

String =  500Type=  <class>Float =  500.0Type =  <class>Integer =  500Type =  <class></class></class></class>

将字符串转换为数字base10和base8

示例

在此示例中,我们将使用带有基本参数的 int() 将字符串转换为数字。

立即学习“Python免费学习笔记(深入)”;

# String to be convertedmyStr = "500"# Display the string and it's typeprint("String = ",myStr)print("Type= ", type(myStr))# Convert the string to intmyInt1 = int(myStr)print("Integer (base10) = ", myInt1)print("Type = ", type(myInt1))# Convert the string to intmyInt2 = int(myStr, base=8)print("Integer (base8) = ", myInt2)print("Type = ", type(myInt2))

输出

String =  500Type=  <class>Integer (base10) =  500Type =  <class>Integer (base8) =  320Type =  <class></class></class></class>