python数据类型转换

Python 数据类型转换可以分为两种:

  • 隐式类型转换 - 自动完成
  • 显式类型转换 - 需要使用类型函数来转换

隐式类型转换是自动完成的,如:

复制代码
num_int = 123
num_flo = 1.23

num_new = num_int + num_flo

print("datatype of num_int:",type(num_int))
print("datatype of num_flo:",type(num_flo))

print("Value of num_new:",num_new)
print("datatype of num_new:",type(num_new))
复制代码

结果:

num_int 数据类型为: <class 'int'>
num_flo 数据类型为: <class 'float'>
num_new: 值为: 124.23
num_new 数据类型为: <class 'float'>

python会自动将低精度的数据类型转化为高精度的数据类型,但有些时候隐式类型转换无法满足需求,如:

num_int = 123
num_str = "456"

print("Data type of num_int:",type(num_int))
print("Data type of num_str:",type(num_str))

print(num_int+num_str)

结果:

num_int 数据类型为: <class 'int'>
num_str 数据类型为: <class 'str'>
Traceback (most recent call last):
  File "/runoob-test/test.py", line 7, in <module>
    print(num_int+num_str)
TypeError: unsupported operand type(s) for +: 'int' and 'str'

从输出中可以看出,整型和字符串类型运算结果会报错,输出 TypeError。 Python 在这种情况下无法使用隐式转换。这时候就需要用到显示类型转换。

复制代码
x = int(1)   # x 输出结果为 1
y = int(2.8) # y 输出结果为 2
z = int("3") # z 输出结果为 3
x = float(1)     # x 输出结果为 1.0
y = float(2.8)   # y 输出结果为 2.8
z = float("3")   # z 输出结果为 3.0
w = float("4.2") # w 输出结果为 4.2
x = str("s1") # x 输出结果为 's1'
y = str(2)    # y 输出结果为 '2'
z = str(3.0)  # z 输出结果为 '3.0'
复制代码

上述是将数据转化为整型、浮点型、字符串

常用的显示转化如下:

int(x [,base])   将x转换为一个整数,转化十进制也用它

float(x)   将x转换到一个浮点数

str(x)   将对象 x 转换为字符串

list(s)   将序列 s 转换为一个列表

set(s)  转换为可变集合

dict(d)  创建一个字典。d 必须是一个 (key, value)元组序列

chr(x)  将一个整数转换为一个字符

ord(x)  将一个字符转换为它的整数值,即获取一个字符的ASCII码

hex(x) 将一个整数转换为一个十六进制字符串

oct(x) 将一个整数转换为一个八进制字符串

来自菜鸟教程

posted @   *小白*  阅读(573)  评论(0编辑  收藏  举报
相关博文:
阅读排行:
· 无需6万激活码!GitHub神秘组织3小时极速复刻Manus,手把手教你使用OpenManus搭建本
· C#/.NET/.NET Core优秀项目和框架2025年2月简报
· Manus爆火,是硬核还是营销?
· 终于写完轮子一部分:tcp代理 了,记录一下
· 【杭电多校比赛记录】2025“钉耙编程”中国大学生算法设计春季联赛(1)
点击右上角即可分享
微信分享提示