字符串、列表、元组之间的相互转换

字符串、列表、元组之间的相互转换主要使用是三个函数:str(),tuple(),list()和join()

#字符串——>列表
str1 = 'hello world'
lis = list(str1)
print('输出结果是:',lis) #该函数将字符串拆分成最小的元素然后组成列表。
输出结果是: ['h', 'e', 'l', 'l', 'o', ' ', 'w', 'o', 'r', 'l', 'd']
#字符串——>元组
str1 = 'hello world'
tu1 = tuple(str1)#该函数将字符串拆分成最小的元素然后组成元组
print(tu1)
('h', 'e', 'l', 'l', 'o', ' ', 'w', 'o', 'r', 'l', 'd')
#列表——>字符串
lis = ['h', 'e', 'l', 'l', 'o', ' ', 'w', 'o', 'r', 'l', 'd']
str1 =  ''.join(lis)#以空字符串''连接lis中的每个元素
print(str1)
hello world
#列表——>元组
lis = ['h', 'e', 'l', 'l', 'o', ' ', 'w', 'o', 'r', 'l', 'd']
tu1 = tuple(lis)#tuple函数将列表转换为元组
print(tu1)
('h', 'e', 'l', 'l', 'o', ' ', 'w', 'o', 'r', 'l', 'd')
#元组——>字符串
tu1 = ('h', 'e', 'l', 'l', 'o', ' ', 'w', 'o', 'r', 'l', 'd')
str1 = ''.join(tu1)#以空字符串''连接元组中的每个元素
print(str1)
hello world
#元组——>列表
tu1 = ('h', 'e', 'l', 'l', 'o', ' ', 'w', 'o', 'r', 'l', 'd')
lis = list(tu1)
print(lis)
['h', 'e', 'l', 'l', 'o', ' ', 'w', 'o', 'r', 'l', 'd']

猜你喜欢

转载自blog.csdn.net/Grim777/article/details/81488249
今日推荐