How to Build Strings Using .format()

Often developers try to build strings in Python by concatenating a bunch of strings together to make one long string, which definitely works but isn’t exactly ideal. Python’s .format() method allows you to perform essentially the same effect as concatenating strings (adding a bunch of strings together) but does so in a much more efficient and lightweight manner.

Let’s say you want to add together the following strings to create a sentence:

name = "Jon" 
age = 28 
fave_food = "burritos"
fave_color = "green"
To print the strings above you always have the option to concatenate them, like this:

string = "Hey, I'm " + name + "and I'm " + str(age) + " years old. I love " + fave_food + 
" and my favorite color is " + fave_color "." 
print(string)

OR you can create your string by using the .format() method, like this:

string = "Hey, I'm {0} and I'm {1} years old. I love {2} and my favorite color is {3}.".format(name, 
age, fave_food, fave_color)
print(string)

Your output for both of the above examples would be the same:

Hey, I'm Jon and I'm 28 years old. I love burritos and my favorite color is green.

Though both of the examples above yield the same result of one long string, using the .format() method is much quicker and much more lightweight than the other solution of concatenating strings.

Leave a Reply

Your email address will not be published. Required fields are marked *