如何在Python中将字符串转换为列表?

Ale*_*lar 18 python string list

如何将字符串(如'hello')转换为列表(如[h,e,l,l,o])?

小智 41

list()函数[ 文档 ]将一个字符串转换为单字符字符串列表.

>>> list('hello')
['h', 'e', 'l', 'l', 'o']
Run Code Online (Sandbox Code Playgroud)

即使没有将它们转换为列表,字符串也已经在几个方面表现得像列表.例如,您可以使用括号访问单个字符(作为单字符字符串):

>>> s = "hello"
>>> s[1]
'e'
>>> s[4]
'o'
Run Code Online (Sandbox Code Playgroud)

您还可以遍历字符串中的字符,因为您可以循环遍历列表的元素:

>>> for c in 'hello':
...     print c + c,
... 
hh ee ll ll oo
Run Code Online (Sandbox Code Playgroud)