Padding Substitutions or Generating Spaces
Demonstration of spacing when strings are passed as parameters
By default, strings are left-justified within the field, and numbers are right-justified. We can modify this by placing an alignment code just following the colon.
< : left-align text in the field
^ : center text in the field
> : right-align text in the field
Python3
# To demonstrate spacing when # strings are passed as parameters print ( "{0:4}, is the computer science portal for {1:8}!" . format ( "w3wiki" , "geeks" )) # To demonstrate spacing when numeric # constants are passed as parameters. print ( "It is {0:5} degrees outside !" . format ( 40 )) # To demonstrate both string and numeric # constants passed as parameters print ( "{0:4} was founded in {1:16}!" . format ( "w3wiki" , 2009 )) # To demonstrate aligning of spaces print ( "{0:^16} was founded in {1:<4}!" . format ( "w3wiki" , 2009 )) print ( "{:*^20s}" . format ( "Geeks" )) |
Output :
w3wiki, is the computer science portal for geeks !
It is 40 degrees outside!
w3wiki was founded in 2009!
w3wiki was founded in 2009 !
*******Geeks********
Python String format() Method
The format()
method is a powerful tool that allows developers to create formatted strings by embedding variables and values into placeholders within a template string. This method offers a flexible and versatile way to construct textual output for a wide range of applications. Python string format() function has been introduced for handling complex string formatting more efficiently. Sometimes we want to make generalized print statements in that case instead of writing print statements every time we use the concept of formatting.