Home > Mobile >  Python print() command doesn't print everything on one line
Python print() command doesn't print everything on one line

Time:09-16

Can someone tell me why my output doesn't show every element in my list on one line. Instead it shows underneath each other. I'm not really sure why this is happening.

pon = '         \n   I   \n         '

list = [pon, pon, pon, pon, pon, pon, pon, pon, pon]
for element in list:
    print(element,end='')

CodePudding user response:

Because the '\n' in your string is a character that means new line

Basicly, everytime there's \n in a string, it's gonna make your print go to a new line

You can ''cancel'' the \n by adding a new ''\'' if your objective was printing \n

(like that \\n)

EDIT:

end='' 

means that by itself each print isn't gonna add a new line, but it doesn't count for the one in your string, just the one naturally added by print function

CodePudding user response:

\n is a newline character. You have \ns in your string, so they will be printed as a new line. See this example:

s = 'First line\nSecond line'
print(s)

Output:

First line
Second line

To print a literal \, escape it with another \:

pon = '         \\n   I   \\n         '

This outputs:

         \n   I   \n                  \n   I   \n                  \n   I   \n                  \n   I   \n                  \n   I   \n                  \n   I   \n                  \n   I   \n                  \n   I   \n                  \n   I   \n

Notes:

  1. Using a keyword like list as a variable name id not encouraged. Use something like my_list instead
  2. Instead of [pon, pon, pon, pon, pon, pon, pon, pon, pon], use [pon] * 10

CodePudding user response:

Also you can use repr for string to print in with \n

pon = "       \n   I   \n       "

list = [pon, pon, pon, pon, pon, pon, pon, pon, pon]
for element in list:
    print(repr(element),end='')

Output:

'       \n   I   \n       ''       \n   I   \n       ''       \n   I   \n       ''       \n   I   \n       ''       \n   I   \n       ''       \n   I   \n       ''       \n   I   \n       ''       \n   I   \n       ''       \n   I   \n       '
  • Related