Str.format()

str.format() works by putting in one or more replacement fields and placeholders defined by a pair of curly braces { } into a string. The value we wish to put into the placeholders and concatenate with the string passed as parameters into the format function. 

Example: Formatting strings using the format() method.

Python3




n1 = 'Hello'
n2 = 'w3wiki'
 
# for single substitution
print('{}, {}'.format(n1, n2))


Output

Hello, w3wiki




We can also use the variable name inside the curly braces {}. This will allow us to use the parameters of format functions in any order we want.

Example: Format functions with variables inside curly braces.

Python3




n1 = "Hello"
n2 = "w3wiki"
 
# for single or multiple substitutions
# let's say b1 and b2 are formal parameters
# and n1 and n2 are actual parameters
print("{b1}! This is {b2}.".format(b1=n1, b2=n2))
 
# we can also change the order of the
# variables in the string without changing
# the parameters of format function
print("{b2}! This is {b1}.".format(b1=n1, b2=n2))


Output

Hello! This is w3wiki.
w3wiki! This is Hello.




Note: To know more about str.format(), refer to format() function in Python

Python String InterpolationPython String Interpolation

String Interpolation is the process of substituting values of variables into placeholders in a string. Let’s consider an example to understand it better, suppose you want to change the value of the string every time you print the string like you want to print “hello <name> welcome to geeks for geeks” where the <name> is the placeholder for the name of the user. Instead of creating a new string every time, string interpolation in Python can help you to change the placeholder with the name of the user dynamically. 

Python String Interpolation

Similar Reads

% – Formatting

% – Formatting is a feature provided by Python that can be accessed with a % operator. This is similar to the printf style function in C....

Str.format()

...

f-strings

str.format() works by putting in one or more replacement fields and placeholders defined by a pair of curly braces { } into a string. The value we wish to put into the placeholders and concatenate with the string passed as parameters into the format function....

String Template Class

...

Contact Us