Python Forum
Undesired space after using \n in print - Printable Version

+- Python Forum (https://python-forum.io)
+-- Forum: Python Coding (https://python-forum.io/forum-7.html)
+--- Forum: General Coding Help (https://python-forum.io/forum-8.html)
+--- Thread: Undesired space after using \n in print (/thread-32758.html)



Undesired space after using \n in print - Tuxedo - Mar-03-2021

This has been bugging me for a long time. The output has the first line shifted one space to the right. How to avoid the extra space?

x =[1, 2, 3]
print('\n',x)
print(x)
Output:
[1, 2, 3] [1, 2, 3]



RE: Undesired space after using \n in print - Gribouillis - Mar-03-2021

Try
print('\n', x, sep='')



RE: Undesired space after using \n in print - snippsat - Mar-03-2021

>>> help(print)
Help on built-in function print in module builtins:

print(...)
    print(value, ..., sep=' ', end='\n', file=sys.stdout, flush=False)
    
    Prints the values to a stream, or to sys.stdout by default.
    Optional keyword arguments:
    file:  a file-like object (stream); defaults to the current sys.stdout.
    sep:   string inserted between values, default a space.
    end:   string appended after the last value, default a newline.
    flush: whether to forcibly flush the stream.
So this give a hint that newlineđź‘€ is default.
x = [1, 2, 3]
print(x)
print(x)
Output:
[1, 2, 3] [1, 2, 3]



RE: Undesired space after using \n in print - Tuxedo - Mar-03-2021

Thanks! I figured it must be something simple. I've tried several internet searches but never could figure out the right wording of the search.


RE: Undesired space after using \n in print - snippsat - Mar-03-2021

Also look at f-string as it's much more powerful for formatting output that messing with print parameters.
x = [1, 2, 3]
for i in x:
    print(f'{i:<{i}}{x}')
Output:
1[1, 2, 3] 2 [1, 2, 3] 3 [1, 2, 3]
>>> for word in 'f-strings are cool'.split():
...     print(f'{word.upper():~^20}')
...     
~~~~~F-STRINGS~~~~~~
~~~~~~~~ARE~~~~~~~~~
~~~~~~~~COOL~~~~~~~~