我如何将一个句子分成变量,然后列出它

时间:2018-04-16 04:59:33

标签: python list split

我需要一个句子或一组单词,将每个单词拆分成一个单独的变量,然后列出它们。这就是我到目前为止所做的:

sentence = input('Please type a sentence:')
sentence.split(" ")

words = []
words.extend([sentence.split(" ")])
print(words)

我使用单词"one two three"作为输入来测试代码。使用此示例句子,预期输出为[one, two, three]然后,我应该能够在以后对所有单独的变量进行处理:words[2]

问题是列表"words"仅接收拆分句子作为一个变量单个变量,因此输出变为[[one, two, three]]并且技术上只有一个变量。

另外:我是一般的编程人员,这是我的第一篇文章所以,请原谅我,如果我错过了一些显而易见的东西,

5 个答案:

答案 0 :(得分:3)

使用

words = sentence.split(" ")

应该解决你的问题。 split本身会返回一个列表。

答案 1 :(得分:0)

split它会自动返回一个列表,然后再次放入另一个[],以便它嵌套

words.extend(sentence.split(" "))

或者您可以直接指定上面的列表

words = sentence.split(' ')
print (words)

#out
[one, two, three]

答案 2 :(得分:0)

sentence = input('Please type a sentence:')
templist = sentence.split(" ")

words = []
for x in templist:
    words.append(x)
print(words)

OR

替代:

sentence = input('Please type a sentence:')
words = sentence.split(" ")
print(words)

说明:

将句子设为sentence变量

sentence = input('Please type a sentence:')

使用split函数拆分句子,将空格作为分隔符并存储在templist

templist = sentence.split(" ")

迭代templist中的单词并将每个单词追加到words list

for x in templist:
words.append(x)

答案 3 :(得分:0)

您正在将列表传递给“单词”(已经是列表)。你可以做以下两件事之一:

  • 使用:words = sentence.split(" ")
  • 如果您想稍后添加更多条目,并想使用扩展功能,请使用:

    words = [] words.extend(sentence.split(" "))

希望这有帮助。

答案 4 :(得分:0)

试试这个

words = []

def split(sentence):
    words = sentence.split(" ")
    return words


words = split("and the duck said: Woof")
print(words)

代码非常自我解释,但为了完成:

  1. 我创建了一个名为words

  2. 的数组
  3. 我创建了一个为我们分割句子的函数

  4. 我调用该函数并将单词返回

  5. ,输出看起来像这样

      

    ['和',''','鸭子','说:','Woof']

相关问题