Edicury
Edicury

Reputation: 3

Print all words in a String without split() function

I want to print out all words in a string, line by line without using split() funcion in Python 3.

The phrase is a str(input) by the user, and it has to print all the words in the string, no matter it's size.Here's my code:

my_string = str(input("Phrase: "))
tam = len(my_string)



s = my_string
ch = " "
cont = 0
for i, letter in enumerate(s):
    if letter == ch:
        #print(i)
        print(my_string[cont:i])
        cont+=i+1

The output to this is:

Phrase: Hello there my friend

Hello
there

It is printing only two words in the string, and I need it to print all the words , line by line.

Upvotes: 0

Views: 1184

Answers (2)

NaN
NaN

Reputation: 2312

My apologies, if this isn't a homework question, but I will leave you to figure out the why.

a = "Hello there my friend"
b = "".join([[i, "\n"][i == " "] for i in a])
print(b)
Hello
there
my
friend

Some variants you can add to the process which you can't get easily with if-else syntax:

print(b.Title())  # b.lower() or b.upper()
Hello
There
My
Friend

Upvotes: 1

anarchokawaii
anarchokawaii

Reputation: 116

def break_words(x):
    x = x + " " #the extra space after x is nessesary for more than two word strings
    strng = ""
    for i in x: #iterate through the string
        if i != " ": #if char is not a space
            strng = strng+i #assign it to another string
        else:
            print(strng) #print that new string
            strng = "" #reset new string
break_words("hell o world")

output:
   hell
   o
   world

Upvotes: 0

Related Questions