开发者

How can I turn a string into a list in Python? [duplicate]

This question already has answers here: How do I split a string into a list of characters? (15 answers) Closed 6 years ago.

How can I turn a string (like 'hello') into a list (l开发者_C百科ike [h,e,l,l,o])?


The list() function [docs] will convert a string into a list of single-character strings.

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

Even without converting them to lists, strings already behave like lists in several ways. For example, you can access individual characters (as single-character strings) using brackets:

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

You can also loop over the characters in the string as you can loop over the elements of a list:

>>> for c in 'hello':
...     print c + c,
... 
hh ee ll ll oo
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜