String format() with multiple placeholders
Multiple pairs of curly braces can be used while formatting the string in Python. Let’s say another variable substitution is needed in the sentence, which can be done by adding a second pair of curly braces and passing a second value into the method. Python will replace the placeholders with values in order.
Syntax : { } { } .format(value1, value2)
Parameters : (value1, value2) : Can be integers, floating point numeric constants, strings, characters and even variables. Only difference is, the number of values passed as parameters in format() method must be equal to the number of placeholders created in the string.
Errors and Exceptions :
IndexError : Occurs when string has an extra placeholder, and we didn’t pass any value for it in the format() method. Python usually assigns the placeholders with default index in order like 0, 1, 2, 3…. to access the values passed as parameters. So when it encounters a placeholder whose index doesn’t have any value passed inside as parameter, it throws IndexError.
Python program using multiple placeholders to demonstrate str.format() method.
Python3
# Multiple placeholders in format() function my_string = "{}, is a {} science portal for {}" print (my_string. format ( "w3wiki" , "computer" , "geeks" )) # different datatypes can be used in formatting print ( "Hi ! My name is {} and I am {} years old" . format ( "User" , 19 )) # The values passed as parameters # are replaced in order of their entry print ( "This is {} {} {} {}" . format ( "one" , "two" , "three" , "four" )) |
Output
w3wiki, is a computer science portal for geeks
Hi! My name is User and I am 19 years old
This is one two three four
String format() IndexError
Python program demonstrating Index error number of placeholders is four but there are only three values passed.
Python3
# parameters in format function. my_string = "{}, is a {} {} science portal for {}" print (my_string. format ( "w3wiki" , "computer" , "geeks" )) |
Output
IndexError: tuple index out of range
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.