convert a word to a list of chars [duplicate]

2020-04-16 02:40发布

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 "".

标签: python
5条回答
疯言疯语
2楼-- · 2020-04-16 02:54

list(word)

you can pass it to list

>>> list('word')
['w', 'o', 'r', 'd']
查看更多
仙女界的扛把子
3楼-- · 2020-04-16 02:55

In Python string is iterable. This means it supports special protocol.

>>> 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 constructor may build list of any iterable. It relies on this special method next and gets letter by letter from string until it encounters StopIteration.

So, the easiest way to make a list of letters from string is to feed it to list constructor:

>>> list(s)
['1', '2', '3']
查看更多
别忘想泡老子
4楼-- · 2020-04-16 03:07

You can iterate over each letter in a string like this:

>>> word = "word"
>>> for letter in word:
...     print letter;
...
w
o
r
d
>>>
查看更多
够拽才男人
5楼-- · 2020-04-16 03:08
>>> s = "foobar"
>>> list(s)
['f', 'o', 'o', 'b', 'a', 'r']
查看更多
地球回转人心会变
6楼-- · 2020-04-16 03:09

In python send it to

    list(word)
查看更多
登录 后发表回答