简体   繁体   中英

Print statement creates an unwanted newline

I am trying to go through a long list of words, and print both the lowercase word and the uppercase word (default) to the screen in the same line. Here is my code:

for word in word_list:

    print("Here is: {0} and {1}".format(word.lower(), word))

However, this has the output (showcasing only two words):

Here is: word1 
 and WORD1

Here is: word2 and WORD2

I have not been able to get rid of the newline between word1 and WORD1. It does not appear to happen for the last word I try and print. Any ideas as to why, and how to overcome this?

Here's an example to reproduce your issue:

In [1411]: word = 'WORD1\n'

In [1412]: print("Here is: {0} and {1}".format(word.lower(), word))
Here is: word1
 and WORD1

Notice the trailing newline. One of your list elements has those. You can remove it using str.strip .

In [1413]: word = word.strip(); print("Here is: {0} and {1}".format(word.lower(), word))
Here is: word1 and WORD1

You can also use str.rstrip , ( r => right) if there's only the possibility of trailing whitespace chars (not leading ones).

On a related note, I'd recommend taking a look at Rubber Duck Debugging .

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