目录
Python数据类型转换
Python类型转换综述
Python中数据类型有很多,它们之间经常需要相互转换。常见的转换有以下几种。
- 字符与字节之间的转换(见上一篇字节串类型)
- 进制之间的转换(见上一篇字节串类型篇)
- 字符与进制之间的转换(见上一篇字节串类型篇)
- 数字与字符之间的转换
- 列表与元组之间的转换
- 列表与可迭代对象之间的转换
- 列表与字符串之间的转换
int、float、str之间的转换
数字与字符之间的转换指的是int、float、str之间的转换,转换函数分别为int()、float()、str()。
a=3
b=3.5
c="3"
d="3.5"
print(type(a),a) # <class 'int'> 3
print(type(b),b) # <class 'float'> 3.5
print(type(c),c) # <class 'str'> 3
print(type(d),d) # <class 'str'> 3.5
a=int(3)
b=int(3.5)
c=int("3")
# d=int("3.5") # 报错 ValueError: invalid literal for int() with base 10: '3.5'
print(type(a),a) # <class 'int'> 3
print(type(b),b) # <class 'int'> 3
print(type(c),c) # <class 'int'> 3
# print(type(d),d)
a=float(3)
b=float(3.5)
c=float("3")
d=float("3.5") # 报错 ValueError: invalid literal for int() with base 10: '3.5'
print(type(a),a) # <class 'float'> 3.0
print(type(b),b) # <class 'float'> 3.5
print(type(c),c) # <class 'float'> 3.0
print(type(d),d) # <class 'float'> 3.5
列表与元组之间的转换
列表与元组之间的转换分别使用list()和tuple()函数。
alist=[1,2,3]
atuple=(1,2,3,4,5,6,7,8)
print(type(alist),alist) # <class 'list'> [1, 2, 3]
print(type(atuple),atuple) # <class 'tuple'> (1, 2, 3, 4, 5, 6, 7, 8)
alist2=list(atuple)
atuple2=tuple(alist)
print(type(alist2),alist2) # <class 'list'> [1, 2, 3, 4, 5, 6, 7, 8]
print(type(atuple2),atuple2) # <class 'tuple'> (1, 2, 3)
列表与可迭代对象之间的转换
可迭代对象需要通过循环取值,每次循环只能取一个值。
a=range(5)
print(type(a),a) # <class 'range'> range(0, 5)
# 循环(迭代)取值
for i in a:
print(i)
alist=list(a) # 把可迭代对象转换成list对象
print(type(alist),alist) # <class 'list'> [0, 1, 2, 3, 4]
运行结果
C:UsershccmaAnaconda3python.exe E:/wkp01/p00/test01/py001/t09.py
<class 'range'> range(0, 5)
0
1
2
3
4
<class 'list'> [0, 1, 2, 3, 4]
Process finished with exit code 0
序列与字符串之间的转换
序列与字符串之间的转换主要使用字符串函数str.join()与str.split()。
序列(列表与元组)转字符串,使用字符串拼接函数str.join()。
sep="" # sep 可以是空字符串,也可是任意分隔,比如:-,;等
alist=["1","2","3","4","5","6"] # 要求序列内元素都是字符串
# alist=[1,2,3,4,5,6] # join时报错 TypeError: sequence item 0: expected str instance, int found
print(sep.join(alist)) # 123456
sep=","
atuple=("1","2","3")
print(sep.join(atuple)) # 1,2,3
字符串转列表,使用字符串分割函数str.split()。
str1="123456"
str2="1 2 3 4 5 6"
str3="1,2,3,4,5,6"
str4="1-2-3-4-5-6"
str5="hello world"
print(str1.split()) # ['123456']
print(str2.split(" ")) # ['1', '2', '3', '4', '5', '6']
print(str3.split(",")) # ['1', '2', '3', '4', '5', '6']
print(str4.split("-")) # ['1', '2', '3', '4', '5', '6']
print(str5.split(" ")) # ['hello', 'world']
print(str5.split("o")) # ['hell', ' w', 'rld']