Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Remove newline from for looped words

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:

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>> 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.

>Solution :

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
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading