Python(三)数据类型转换


程序员的公众号:源1024,获取更多资料, 无加密无套路!

最近整理了一份大厂面试资料《史上最全大厂面试题》,Springboot、微服务、算法、数据结构、Zookeeper、Mybatis、Dubbo、linux、Kafka、Elasticsearch、数据库等等
获取方式: 关注公众号并回复 666 领取,更多内容持续奉上


数据类型转换

1、隐式类型转换

python 复制代码
a = 12
b = 1.2
c = a + b

print("a 数据类型为:",type(a))
print("b 数据类型为:",type(b))

print("c 值为:",c)
print("c 数据类型为:",type(c))

#输出
a 数据类型为: <class 'int'>
b 数据类型为: <class 'float'>
c 值为: 13.2
c 数据类型为: <class 'float'>

int类型与float类型计算结果是float类型,Python 会将较小的数据类型转换为较大的数据类型,以避免数据丢失。

python 复制代码
a = 123
b = "456"

print("a 数据类型为:",type(a))
print("b 数据类型为:",type(b))
print(a+b)
#输出

a 数据类型为: <class 'int'>
b 数据类型为: <class 'str'>
Traceback (most recent call last):
    print(a+b)
TypeError: unsupported operand type(s) for +: 'int' and 'str'

整型和字符串类型运算结果会报错,输出 TypeError。 Python 在这种情况下无法使用隐式转换,Python 提供了一种解决方案,称为显式转换

2、显式类型转换

显式类型转换中,可以使用预定义函数将对象的数据类型转换为所需的数据类型。

|------------------------------------------------------------------------------------------------------------|----------------------------------|
| 函数 | 描述 |
| int(x ,base) | 将x转换为一个整数 |
| float(x) | 将x转换到一个浮点数 |
| complex(real ,imag) | 创建一个复数 |
| str(x) | 将对象 x 转换为字符串 |
| repr(x) | 将对象 x 转换为表达式字符串 |
| eval(str) | 用来计算在字符串中的有效Python表达式,并返回一个对象 |
| tuple(s) | 将序列 s 转换为一个元组 |
| list(s) | 将序列 s 转换为一个列表 |
| set(s) | 转换为可变集合 |
| dict(d) | 创建一个字典。d 必须是一个 (key, value)元组序列。 |
| frozenset(s) | 转换为不可变集合 |
| chr(x) | 将一个整数转换为一个字符 |
| ord(x) | 将一个字符转换为它的整数值 |
| hex(x) | 将一个整数转换为一个十六进制字符串 |
| oct(x) | 将一个整数转换为一个八进制字符串 |

int() 强制转换为整型

python 复制代码
a = int(2.3)
b = int("12")
print(a)   #输出 2
print(b)   #输出 12

float() 强制转换为浮点型

python 复制代码
a = float(11)    
b = float(2.2)  
c = float("13")   
d = float("3.14") 

print(a)
print(b)
print(c)
print(d)

#输出
11.0
2.2
13.0
3.14

str() 强制转换为字符串类型

python 复制代码
a = str("aa") 
b = str(23)    
c = str(3.14)  

print(a)
print(b)
print(c)

#输出
aa
23
3.14

不同类型进行计算

python 复制代码
a = 123
b = "456"

print("a 数据类型为:",type(a))
print("b 数据类型为:",type(b))
print(a + int(b))

#输出
a 数据类型为: <class 'int'>
b 数据类型为: <class 'str'>
579

其他函数使用:

python 复制代码
print(chr(65))
print(ord('A'))
print(hex(11))
print(oct(11))

#输出
A
65
0xb
0o13
相关推荐
aqi004 小时前
15天学会AI应用开发(八)使用向量数据库实现RAG功能
人工智能·python·大模型·ai编程·ai应用
Csvn5 小时前
`functools.lru_cache` —— 一行代码搞定缓存加速
后端·python
金銀銅鐵1 天前
[Python] 从《千字文》中随机挑选汉字
后端·python
cup111 天前
[技术复盘] Windows Python 打包实战:Nuitka 环境踩坑总结与 CI 自动化构建全指南
python·ai·环境变量·ci·nuitka·skill
aqi001 天前
15天学会AI应用开发(七)有了大模型为什么还要引入RAG
人工智能·python·大模型·ai编程·ai应用
金銀銅鐵1 天前
用 Python 实现 Take-Away 游戏
python·游戏
copyer_xyf1 天前
Agent 流程编排
后端·python·agent
copyer_xyf1 天前
Agent RAG
后端·python·agent