2011-09-22 32 views
9

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

+4

请注意,该列表将是字符串,'['h','e','l','l','o']'。 – nmichaels

+7

Python中的字符串表现得像字符列表。例如。 ''hello'[1]' - >''e''。你确定你需要一个清单吗? –

+0

@PeterGraham:好的,我在这个答案中加入了一些描述。 –

回答

28

list()函数[docs]会将字符串转换为单字符串列表。

>>> list('hello') 
['h', 'e', 'l', 'l', 'o'] 

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

>>> s = "hello" 
>>> s[1] 
'e' 
>>> s[4] 
'o' 

你也可以遍历字符串中的字符,你可以在列表中的元素循环:

>>> for c in 'hello': 
...  print c + c, 
... 
hh ee ll ll oo 
相关问题