python中是否有一个函数可以将单词拆分成单个字母列表? e.g:

s="Word to Split"

获取

wordlist=['W','o','r','d','','t','o' ....]
有帮助吗?

解决方案

>>> list("Word to Split")
['W', 'o', 'r', 'd', ' ', 't', 'o', ' ', 'S', 'p', 'l', 'i', 't']

其他提示

最简单的方法可能只是使用 list(),但至少还有一个其他选项:

s = "Word to Split"
wordlist = list(s)               # option 1, 
wordlist = [ch for ch in s]      # option 2, list comprehension.

他们应两者为您提供所需内容:

['W','o','r','d',' ','t','o',' ','S','p','l','i','t']

如上所述,第一个可能是最适合您的示例,但有一些用例可能使后者对于更复杂的东西非常方便,例如,如果您想对项目应用一些任意函数,例如:

[doSomethingWith(ch) for ch in s]

滥用规则,结果相同:     (x代表'要分裂的词'中的x)

实际上是一个迭代器,而不是一个列表。但是你很可能不会真的在意。

list函数将执行此操作

>>> list('foo')
['f', 'o', 'o']
text = "just trying out"

word_list = []

for i in range(0, len(text)):
    word_list.append(text[i])
    i+=1

print(word_list)

['j', 'u', 's', 't', ' ', 't', 'r', 'y', 'i', 'n', 'g', ' ', 'o', 'u', 't']
许可以下: CC-BY-SA归因
不隶属于 StackOverflow
scroll top