Python Forum
print() examples - 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: print() examples (/thread-29169.html)



print() examples - leodavinci1990 - Aug-21-2020

print('%10s' % ('test',))
What is the purpose or difference between the having the colon after the 'text' string as in code above and without it as in code below:

print('%10s' % ('test')
The two pieces of code seem to do the same thing!


RE: print() examples - ibreeden - Aug-21-2020

Python 3.6.9 (default, Jul 17 2020, 12:50:27) 
[GCC 8.4.0] on linux
Type "help", "copyright", "credits" or "license" for more information.
>>> type(('hallo',))
<class 'tuple'>
>>> type(('hallo'))
<class 'str'>



RE: print() examples - Axel_Erfurt - Aug-21-2020

you can add a third one

print('%10s' % ('test',))
print('%10s' % ('test'))
print(f'{" "*5} test')
Output:
test test test



RE: print() examples - snippsat - Aug-21-2020

The third one that @Axel_Erfurt show can also be more elegant.
>>> print(f'{" "*5} test')
      test
>>> print(f'{"test":>10}')
      test  
So @leodavinci1990 the old string formatting %s should not be used anymore,use f-string
>>> h = 'hello'
>>> w = 'world'
>>> print(f'{h:^10}{w:>10}')
  hello        world
>>> print(f'{h:<10}{w:<10}')
hello     world     
>>> print(f'{h:^10}{w:^10}')
  hello     world   
>>> print(f'{h:>10}{w:>10}')
     hello     world

>>> # f-strings support any Python expressions inside the curly braces
>>> a, b = 5, 7
>>> f'{a}/{b} = {a/b:.2}' # limit to two decimal places 
'5/7 = 0.71'

>>> for word in 'f-strings are awesome'.split():
...     print(f'{word.upper():~^20}')
~~~~~F-STRINGS~~~~~~
~~~~~~~~ARE~~~~~~~~~
~~~~~~AWESOME~~~~~~~