python中字符串和列表之间的转换

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)

python中字符串和列表之间的转换

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)))

python中字符串和列表之间的转换


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中字符串和列表之间的转换

 

文章出处登录后可见!

已经登录?立即刷新

共计人评分,平均

到目前为止还没有投票!成为第一位评论此文章。

(0)
扎眼的阳光的头像扎眼的阳光普通用户
上一篇 2023年3月11日
下一篇 2023年3月11日

相关推荐