Format Strings

 

Format Strings

What if we want to join two separated strings?

We can perform concatenation to join two or more separate strings.

Example:

str4 = "Captain"
str5 = "America"
str6 = str4 + " " + str5
print(str6)

Output:

Captain America

 

In the above example, we saw how one can concatenate two strings. But how can we concatenate a string and an integer? 

name = "Maxon"
age = 18
print("My name is" + name + "and my age is" + age)

Output:

TypeError: can only concatenate str (not "int") to str

As we can see, we cannot concatenate a string to another data type.

 

So what’s the solution?

We make the use of format() method. The format() methods places the arguments within the string wherever the placeholders are specified.

Example:

name = "Maxon"
age = 18
statement = "My name is {} and my age is {}."
print(statement.format(name, age)) 

Output:

My name is Naxon and my age is 18.

 

We can also make the use of indexes to place the arguments in specified order.

Example:

quantity = 2
fruit = "Apples"
cost = 120.0
statement = "I want to buy {2} dozen {0} for {1}$"
print(statement.format(fruit,cost,quantity))

Output:

I want to buy 2 dozen Apples for $120.0