Python Forum
Thread Rating:
  • 0 Vote(s) - 0 Average
  • 1
  • 2
  • 3
  • 4
  • 5
print() examples
#1
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!
Reply
#2
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'>
Reply
#3
you can add a third one

print('%10s' % ('test',))
print('%10s' % ('test'))
print(f'{" "*5} test')
Output:
test test test
Reply
#4
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~~~~~~~
Reply


Possibly Related Threads…
Thread Author Replies Views Last Post
  Super flexibility in python, examples Kakha 10 3,808 Jan-08-2021, 12:40 AM
Last Post: Skaperen
  Examples of Customer requirements ComputerAstronaut 1 1,833 Dec-08-2020, 03:22 AM
Last Post: Larz60+
  mpi4py examples/tutorials MuntyScruntfundle 1 2,687 Dec-01-2018, 10:22 PM
Last Post: Larz60+

Forum Jump:

User Panel Messages

Announcements
Announcement #1 8/1/2020
Announcement #2 8/2/2020
Announcement #3 8/6/2020