Formatting Strings in Python

Original article was published by Luay Matalka on Artificial Intelligence on Medium


Using the format() Method

One way to accomplish this would be to use the format method. The format() method is a string method. Once you call it off a string, it would replace all the curly brackets in the string with the values of the variables passed in the parenthesis, in the order they are passed in. Thus, the curly brackets act as placeholders for the variables.

For example, to use the format method for the above example, we would use the following code:

first_name = 'John'
last_name = 'Doe'
age = 43
sentence = '{} {} is {} years old'.format(first_name, last_name, age)print(sentence)
# 'John Doe is 43 years old'

Note: The format method will replace the curly brackets with the values of the variables in the order they appear within the parenthesis.

If we don’t want to worry about passing the variables in the correct order, we can use keys in each curly bracket and later assign the variable for that specific key:

first_name = 'John'
last_name = 'Doe'
age = 43
sentence = '{first} {last} is {age_yrs} years old'.format(last=last_name, age_yrs=age, first=first_name)print(sentence)
# 'John Doe is 43 years old'

Note how the variables don’t have to be passed in the correct order if we use specific keys for each placeholder.

Though the format() method does the job, there is a much more elegant way of formatting strings, and that’s by using f-strings.