Python 将单词转换为字符列表
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/15418561/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
convert a word to a list of chars
提问by user1103294
I can split a sentence into individual words like so:
我可以将一个句子拆分为单个单词,如下所示:
string = 'This is a string, with words!'
string.split(" ")
['This', 'is', 'a', 'string,', 'with', 'words!']
But I don't know how to split a word into letters:
但我不知道如何将单词拆分为字母:
word = "word"
word.split("")
Throws me an error. Ideally I want it to return ['w','o','r','d'] thats why the split argument is "".
给我一个错误。理想情况下,我希望它返回 ['w','o','r','d'] 这就是为什么 split 参数是“”。
回答by dm03514
list(word)
list(word)
you can pass it to list
你可以把它传递给 list
>>> list('word')
['w', 'o', 'r', 'd']
回答by iblazevic
>>> s = "foobar"
>>> list(s)
['f', 'o', 'o', 'b', 'a', 'r']
回答by CraigTeegarden
You can iterate over each letter in a string like this:
您可以像这样遍历字符串中的每个字母:
>>> word = "word"
>>> for letter in word:
... print letter;
...
w
o
r
d
>>>
回答by Apollo SOFTWARE
In python send it to
在python中将其发送到
list(word)
回答by ovgolovin
In Python string is iterable. This means it supports special protocol.
在 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
listconstructor may build list of any iterable. It relies on this special method nextand gets letter by letter from string until it encounters StopIteration.
list构造函数可以构建任何可迭代的列表。它依赖于这种特殊的方法next,从字符串中逐个字母地获取,直到遇到StopIteration.
So, the easiest way to make a list of letters from string is to feed it to listconstructor:
因此,从字符串制作字母列表的最简单方法是将其提供给list构造函数:
>>> list(s)
['1', '2', '3']

