Python之数据类型转换

1、字符串转换为列表

1 >>> message = "Hi there"
2 >>> ls = list(message)
3 >>> ls
4 ['H', 'i', ' ', 't', 'h', 'e', 'r', 'e']

2、字符串转换为元组

1 >>> message = "Hi there"
2 >>> tp = tuple(message)
3 >>> tp
4 ('H', 'i', ' ', 't', 'h', 'e', 'r', 'e')

3、列表转元组

1 >>> tpl = tuple(ls)
2 >>> tpl
3 ('H', 'i', ' ', 't', 'h', 'e', 'r', 'e')

4、通过range函数创建列表

1 >>> lst = list(range(1,11,2))
2 >>> lst
3 [1, 3, 5, 7, 9]

5、其他转换

 1 >>> a = int(435.6755345)
 2 >>> a
 3 435
 4 >>> b = float(a)
 5 >>> a
 6 435
 7 >>> c = str(a)
 8 >>> c
 9 '435'
10 >>> d = int(True)
11 >>> d
12 1
13 >>> e = str(True)
14 >>> e
15 'True'

       通过range函数创建列表可知,list或者tuple函数的参数不需要是另一个集合,它可以是任何可迭代的对象。可迭代的对象允许程序员使用Python的for循环来访问想的一个序列。

原文地址:https://www.cnblogs.com/fsy12604/p/9901515.html