Formatters with Positional and Keyword Arguments
When placeholders { } are empty, Python will replace the values passed through str.format() in order. The values that exist within the str.format() method are essentially tuple data types and each individual value contained in the tuple can be called by its index number, which starts with the index number 0. These index numbers can be passed into the curly braces that serve as the placeholders in the original string.
Syntax : {0} {1}.format(positional_argument, keyword_argument)
Parameters : (positional_argument, keyword_argument)
- Positional_argument can be integers, floating point numeric constants, strings, characters and even variables.
- Keyword_argument is essentially a variable storing some value, which is passed as parameter.
Example: To demonstrate the use of formatters with positional key arguments.
Python3
# Positional arguments # are placed in order print ( "{0} love {1}!!" . format ( "w3wiki" , "Geeks" )) # Reverse the index numbers with the # parameters of the placeholders print ( "{1} love {0}!!" . format ( "w3wiki" , "Geeks" )) print ( "Every {} should know the use of {} {} programming and {}" . format ( "programmer" , "Open" , "Source" , "Operating Systems" )) # Use the index numbers of the # values to change the order that # they appear in the string print ( "Every {3} should know the use of {2} {1} programming and {0}" . format ( "programmer" , "Open" , "Source" , "Operating Systems" )) # Keyword arguments are called # by their keyword name print ( "{gfg} is a {0} science portal for {1}" . format ( "computer" , "geeks" , gfg = "w3wiki" )) |
Output
w3wiki love Geeks!!
Geeks love w3wiki!!
Every programmer should know the use of Open Source programming and Operating Systems
Every Operating Systems should know the use of Source Open programming and programmer
w3wiki is a computer science portal for 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.