gpt4 book ai didi

python - 将一串单词变成一个列表,所有单词都分开

转载 作者:太空宇宙 更新时间:2023-11-03 13:17:49 25 4
gpt4 key购买 nike

所以我有一大串由空格和制表符分隔的单词,想知道我可以做些什么来快速将每个单独的单词附加到列表中。

例如。

x = "hello Why You it     from the"
list1 = ['hello', 'why', 'you', 'it','from', 'the']

该字符串有制表符和多个空格,因单词而异,我只需要一个快速解决方案而不是手动解决问题

最佳答案

您可以使用 str.split :

>>> x = "hello Why You it from the"
>>> x.split()
['hello', 'Why', 'You', 'it', 'from', 'the']
>>> x = "hello Why You it from the"
>>> x.split()
['hello', 'Why', 'You', 'it', 'from', 'the']
>>>

如果没有任何参数,该方法默认使用空白字符进行拆分。


我刚刚注意到您的示例列表中的所有字符串都是小写的。如果需要,您可以调用 str.lowerstr.split 之前:

>>> x = "hello Why You it from the"
>>> x.lower().split()
['hello', 'why', 'you', 'it', 'from', 'the']
>>>

关于python - 将一串单词变成一个列表,所有单词都分开,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/23936000/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com