在一行中打印每个单词而不是在Python中打印字符?

时间:2018-09-12 14:33:55

标签: python

考虑以下代码和输出

代码1

ls = ["one is one","two is two","three is three"]
for each_item in ls:
    print(each_item) 

输出1:

enter image description here

代码2:

ls = ["one is one","two is two","three is three"]
for each_item in ls:
    for each_word in each_item:
        print(each_word)

输出2:

enter image description here

我的意图是打印如下

  

一个

     

     

一个

     

两个

     

     

两个

     

三个

     

     

三个

在哪里需要修改以按期望的顺序打印?

2 个答案:

答案 0 :(得分:1)

根据taoufik的评论,您想在迭代每个句子之前split。这是因为,默认情况下,当您在Python中遍历字符串时,它将逐字符进行。通过调用split,您可以将字符串(按空格)分成单词列表。见下文。

ls = ["one is one","two is two","three is three"]

for sentence in ls:
    for word in sentence.split():
        print(word)

one
is 
one
two
is
two
three
is
three

答案 1 :(得分:1)

尝试一下:

ls = ["one is one","two is two","three is three"]
words = []
for each_item in ls:
    words = each_item.split()
    for word in words:
        print(word)