xxxxxxxxxx
# default arguments
print("Hello {}, your balance is {}.".format("Adam", 230.2346))
# positional arguments
print("Hello {0}, your balance is {1}.".format("Adam", 230.2346))
# keyword arguments
print("Hello {name}, your balance is {blc}.".format(name="Adam", blc=230.2346))
# mixed arguments
print("Hello {0}, your balance is {blc}.".format("Adam", blc=230.2346))
xxxxxxxxxx
#The {} are replaced by the vairables after .format
new_string = "{} is string 1 and {} is string 2".format("fish", "pigs")
xxxxxxxxxx
# Basic usage
name = "John"
age = 30
print("My name is {} and I am {} years old".format(name, age))
# Specifying placeholders by index
print("My name is {0} and I am {1} years old. {0} is my first name".format(name, age))
# Specifying placeholders by name
print("My name is {name} and I am {age} years old".format(name=name, age=age))
# Formatting numbers
x = 123.456
print("The value of x is {:.2f}".format(x))
In the first example, we're using the format() function to insert the values of name and age into a string. The resulting string will contain the values of the variables in the correct places.
In the second example, we're using index-based placeholders to specify the order of the variables in the string.
In the third example, we're using named placeholders to make the code more readable.
In the fourth example, we're formatting a number (x) to two decimal places using the :.2f format specifier. The resulting string will contain the value of x with two decimal places.
xxxxxxxxxx
# Python string format() method
# default(implicit) order
default_order = "{}, {} and {}".format('John','Bill','Sean')
print('\n--- Default Order ---')
print(default_order)
# order using positional argument
positional_order = "{1}, {0} and {2}".format('John','Bill','Sean')
print('\n--- Positional Order ---')
print(positional_order)
# order using keyword argument
keyword_order = "{s}, {b} and {j}".format(j='John',b='Bill',s='Sean')
print('\n--- Keyword Order ---')
print(keyword_order)