我可以拆分句子爲單個單詞,像這樣:一個字轉換爲字符的列表
string = 'This is a string, with words!'
string.split(" ")
['This', 'is', 'a', 'string,', 'with', 'words!']
但我不知道如何將單詞拆分成字母:
word = "word"
word.split("")
拋出一個錯誤。理想情況下,我希望它返回['w','o','r','d'],這就是爲什麼分割參數是「」。
我可以拆分句子爲單個單詞,像這樣:一個字轉換爲字符的列表
string = 'This is a string, with words!'
string.split(" ")
['This', 'is', 'a', 'string,', 'with', 'words!']
但我不知道如何將單詞拆分成字母:
word = "word"
word.split("")
拋出一個錯誤。理想情況下,我希望它返回['w','o','r','d'],這就是爲什麼分割參數是「」。
list(word)
,你可以把它傳遞給list
>>> list('word')
['w', 'o', 'r', 'd']
>>> s = "foobar"
>>> list(s)
['f', 'o', 'o', 'b', 'a', 'r']
您可以通過每個字母重複在這樣的字符串:
>>> word = "word"
>>> for letter in word:
... print letter;
...
w
o
r
d
>>>
對不起,但那不是'蟒蛇方式' – 2017-03-15 20:16:52
在蟒蛇發送到
list(word)
在Python中,字符串是可迭代的。這意味着它支持特殊協議。
>>> s = '123'
>>> i = iter(s)
>>> i
<iterator object at 0x00E82C50>
>>> i.next()
'1'
>>> i.next()
'2'
>>> i.next()
'3'
>>> i.next()
Traceback (most recent call last):
File "<pyshell#7>", line 1, in <module>
i.next()
StopIteration
list
構造函數可能會構建任何可迭代列表。它依賴於這種特殊的方法next
,並從字符串逐個字母開始,直到它遇到StopIteration
。
因此,爲了從串字母列表的最簡單的方法是將其輸送到list
構造:
>>> list(s)
['1', '2', '3']
你到底想幹什麼?您可以像訪問列表一樣訪問字符串中的單個元素,即'word [0]'會給你'w'。 – Hannele 2013-03-14 19:35:17
是的,這是一個重複的,抱歉沒有找到它。我正在刪除它。 – user1103294 2013-03-14 19:36:47