python 列表、元祖、字符串之间的相互转换和翻转

字符串转列表和元祖

>>> s = 'Hello World'
>>> list(s)
['H', 'e', 'l', 'l', 'o', ' ', 'W', 'o', 'r', 'l', 'd']
>>> tuple(s)
('H', 'e', 'l', 'l', 'o', ' ', 'W', 'o', 'r', 'l', 'd')

列表与元祖互相转换

>>> t = (1,2,4,5)
>>> list(t)
[1, 2, 4, 5]
>>> l = [1,2,3,4]
>>> tuple(l)
(1, 2, 3, 4)

想转成list或tuple都很容易,直接用list()或tuple()就行。

转成字符串:
要用”“.join()

>>> s = 'Hello World'
>>> l = list(s)
>>> l
['H', 'e', 'l', 'l', 'o', ' ', 'W', 'o', 'r', 'l', 'd']
>>> "".join(l)
'Hello World'

>>> t
('H', 'e', 'l', 'l', 'o', ' ', 'W', 'o', 'r', 'l', 'd')
>>> "".join(t)
'Hello World'

翻转列表:
方法1:调用reverse()函数

>>> l = [1,2,3,4,5]
>>> l.reverse()
>>> l
[5, 4, 3, 2, 1]

方法2:

>>> l = [1,2,3,4,5]
>>> l[::-1]
[5, 4, 3, 2, 1]

猜你喜欢

转载自blog.csdn.net/lisa_ren_123/article/details/80677702