misguided
misguided

Reputation: 3789

How to print the words in a string

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

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

Upvotes: 3

Views: 35629

Answers (2)

rajpy
rajpy

Reputation: 2476

Use:

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

Upvotes: 2

jamylak
jamylak

Reputation: 133554

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

    
I
am
testing

Upvotes: 14

Related Questions