目录
- #list
- tup1 = (1,4,6,7)
- ls1 = list(tup1)
- print('转换的列表ls1为:',ls1)
-
-
- tup2 = ('hello','world','funny','window')
- ls2 = list(tup2)
- print('转换的列表ls2为:',ls2)
输出结果为:
- 转换的列表ls1为: [1, 4, 6, 7]
- 转换的列表ls2为: ['hello', 'world', 'funny', 'window']
- ls = {('hello','home','funny','windows','water'), 'come on friends'}
- for element in ls:
- if type(element) == tuple:
- ls1 = list(element)
- print('转换的列表ls为:',ls1)
- elif type(element) == str:
- ls2 = element.split()
- print('转换的列表ls为:',ls2)
- else:
- pass
输出结果:
- 转换的列表ls为: ['hello', 'home', 'funny', 'windows', 'water']
- 转换的列表ls为: ['come', 'on', 'friends']
说明:
①将字符串转为列表类型:list = string.split()
②type函数是用来判断对象是什么数据类型的。
- #tuple
- #简单的用法实例
- ls1 = [1,3,8,6,12,7]
- tup1 = tuple(ls1)
- print('转换的元组tup1为:',tup1)
-
- ls2 = ['hello','world','funny','window']
- tup2 = tuple(ls2)
- print('转换的元组tup2为:',tup2)
-
-
- #与if函数结合使用
- ls3 = ['fine','happy','creative']
- if type(ls3) == list:
- tup3 = tuple(ls3)
- print('转换的元组tup3为:',tup3)
- else:
- pass
输出结果为:
- 转换的元组tup1为: (1, 3, 8, 6, 12, 7)
- 转换的元组tup2为: ('hello', 'world', 'funny', 'window')
- 转换的元组tup3为: ('fine', 'happy', 'creative')
- #string
- #简单的用法实例
- num1 = 543563
- string1 = str(num1)
- print('转换的字符串string1为:',string1)
- print('转换的字符串string1类型为:',type(string1))
-
- num2 = 100086
- string2 = str(num2)
- print('转换的字符串string2为:',string2)
- print('转换的字符串string2类型为:',type(string2))
-
- #与if函数结合使用
- ls = [56340,5983.25,'hello',10086,'happy']
- n = 2
- for i in ls :
- if type(i) == int or type(i) == float:
- n+=1
- string3 = str(i)
- print('转换的字符串string%d为:%s'%(n,string3))
- print('转换的字符串string%d类型为:%s'%(n,type(string3)))
- else:
- pass
输出结果:
- 转换的字符串string1为: 543563
- 转换的字符串string1类型为: <class 'str'>
- 转换的字符串string2为: 100086
- 转换的字符串string2类型为: <class 'str'>
- 转换的字符串string3为:56340
- 转换的字符串string3类型为:<class 'str'>
- 转换的字符串string4为:5983.25
- 转换的字符串string4类型为:<class 'str'>
- 转换的字符串string5为:10086
- 转换的字符串string5类型为:<class 'str'>
参考文章
具体可以参考split函数的用法实例:python如何将字符串进行拆分——split函数的用法及实例_小白修炼晋级中的博客-CSDN博客_python中str.split()的例子
具体if判断语句用法可参考:python的if条件语句的用法及实例_小白修炼晋级中的博客-CSDN博客_python的if条件
具体for函数的用法可参考: