9
如何將字符串(如'hello'
)轉換爲列表(如[h,e,l,l,o]
)?如何在Python中將字符串轉換爲列表?
如何將字符串(如'hello'
)轉換爲列表(如[h,e,l,l,o]
)?如何在Python中將字符串轉換爲列表?
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
請注意,該列表將是字符串,'['h','e','l','l','o']'。 – nmichaels
Python中的字符串表現得像字符列表。例如。 ''hello'[1]' - >''e''。你確定你需要一個清單嗎? –
@PeterGraham:好的,我在這個答案中加入了一些描述。 –