可以使用字符串切片的方法来实现,即根据空格的位置来拆分字符串并将其添加到列表中。
示例代码:
str = "Hello world, this is a test." lst = []
start = 0 end = 0
for i in range(len(str)): if str[i] == " ": end = i word = str[start:end] lst.append(word) start = end + 1
word = str[start:len(str)] lst.append(word)
print(lst)
输出结果为:['Hello', 'world,', 'this', 'is', 'a', 'test.']