Reputation: 13
I am trying to remove the new lines from for-looped words of a paragraph.
code.py
paragraph = 'How are you'
for word in paragraph:
print(word)
Output:
>> H
>> o
>> w
>>
>> a
>> r
>> e
>>
>> y
>> o
>> u
code.py
for word in paragraph:
remove_spacing = ''
new_word = word.replace('\n', '')
It is not changing at all.
I am trying to first loop all the words then attach after it
I also tried using:
new_word = word.rstrip("\n\r")
Expected Output:
>> Howareyou
I have tried many times but it is still not working.
Upvotes: 0
Views: 62
Reputation: 2301
You will want to use something like this:
paragraph = 'How are you'
words = paragraph.split()#get just the words
for word in words: #for each word
print(word, end='')#print and don't go to newline
This will print each word without going to a new line.
Output:
Howareyou
If you want to save to a variable use this:
paragraph = 'How are you'
words = paragraph.split()#get just the words
var = ''
for word in words: #for each word
var += word
print(var)
Output:
Howareyou
Two simpler forms are:
var = "".join(paragraph.split())
print(var)
#and
var = paragraph.replace(" ","")
print(var)
These save to var
in the same way.
Upvotes: 3