Python 如何打印字符串中的单词?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/17205489/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-19 00:45:56  来源:igfitidea点击:

How to printing the words in a string?

pythonstring

提问by misguided

I want to do the following in my code:

我想在我的代码中执行以下操作:

  1. Print each words of a string in a new line
  2. Print each character in a new line
  1. 在新行中打印字符串的每个单词
  2. 在新行中打印每个字符

I have been able to achieve the second part using the following code:

我已经能够使用以下代码实现第二部分:

s2 = "I am testing"
for x in s2:
    print x

I am having trouble achiving the first part . I have written the following code which recognizes where there is space in the string.

我无法完成第一部分。我编写了以下代码来识别字符串中的空格。

for i in s2:
    if not(i.isspace()):
        print i
    else:
        print "space"

Also tried the below which strips all the spaces of the string:

还尝试了以下去除字符串所有空格的方法:

s3 = ''.join([i for i in s2 if not(i.isspace())])
print s3

But still not achieving my desired output, which should be something like:

但仍然没有达到我想要的输出,应该是这样的:

I
am
testing

采纳答案by jamylak

>>> s2 = "I am testing"
>>> for word in s2.split():
        print word


I
am
testing

回答by rajpy

Use:

用:

s2 = "I am testing"
for x in s2.split():
    print x