python内置了list() 和str()强制转换类型的方法,但是在实际的应用中,我们并不能直接就使用这俩个方法进行字符串和列表之间的转换,还需要借助
split() 和join()方法
1、字符串转列表
s = 'hello world hello kitty'
已知字符串s,想把这个字符串转换成list:
print(list(s)) #这种方法也可以转换,但是往往不是我们想要的
result = s.split(' ',2) #['hello', 'world', 'hello kitty']
print(result)
result = s.split(' ',4) #['hello', 'world', 'hello', 'kitty']
print(result)

2、列表转字符串
l = ['h', 'e', 'l', 'l', 'o', ' ', 'w', 'o', 'r', 'l', 'd', ' ', 'h', 'e', 'l', 'l', 'o', ' ', 'k', 'i', 't', 't', 'y']
print(str(l)) #虽然结果转成字符串类型了,但是这明显不是我们想要的结果
print(type(str(l)))

list1 = ['h', 'e', 'l', 'l', 'o', ' ', 'w', 'o', 'r', 'l', 'd', ' ', 'h', 'e', 'l', 'l', 'o', ' ', 'k', 'i', 't', 't', 'y']
result = ''.join(list1)
print(result)
print(type(result))

本文介绍如何在Python中使用split()和join()方法实现字符串和列表的高效转换,包括如何将单个字符串拆分成列表,以及如何将列表合并为一个字符串,通过实例演示了这两种操作的实战应用。
3371

被折叠的 条评论
为什么被折叠?



