简体   繁体   中英

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:

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

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM