user6610400
user6610400

Reputation:

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?

Upvotes: 1

Views: 47

Answers (1)

cs95
cs95

Reputation: 402263

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.

Upvotes: 2

Related Questions