Python Strings Formatting

Python strings formatting is a way to modify the strings according to our needs. There are many different ways to format the strings. Python2 used a % operator to format a string whereas Python3 uses a new way of formatting using a string.format() method. Now, Python3.6+ even supports f-string.

string.format() method

The syntax is: string.format(values)

This method uses a placeholder {} in a string to format a string. This method returns a modified string but doesn’t change the original string. There are three ways to format a string using this method.

a. with an empty placeholder: {}

# Python string.format() example with empty placeholder
original_text = "I love {} becuase of its easy {}."
new_text = original_text.format('Python', 'syntax')
print(new_text)

Output:

I love Python becuase of its easy syntax.

We can also use a predefined variable name as values inside a format parenthesis.

language_name = 'Python'
text = "I love {} programming language."
new_text = text.format(language_name)
print(new_text)

Output:

I love Python programming language.

This method is so powerful that it can even do calculations and place the value in the placeholder.

# Python string.format() for calculation
text = "5 + 9 = {} and 5 - 9 = {}"
ans_text = text.format(5+9, 5-9)
print(ans_text)

Output:

5 + 9 = 14 and 5 - 9 = -4

b. With numbered indices in a placeholder: {index}

# Python string.format() example with index in a placeholder
original_text = "I love {0} becuase of its easy {1}."
new_text = original_text.format('Python', 'syntax')
print(new_text)

original_text = "I love {1} becuase of its easy {0}."
new_text = original_text.format('Python', 'syntax')
print(new_text)

Output:

I love Python becuase of its easy syntax.
I love syntax becuase of its easy Python.

c. With named indices in a placeholder: {name}

# Python string.format() example with name in a placeholder
original_text = "I love {program1} and {program2}."
new_text = original_text.format(program1 = 'Python', program2 = 'javascript')
print(new_text)

Output:

I love Python and javascript.

Python fstring (String Interpolation)

From Python 3.6+, there is a new way of formatting a string that is easy to use and can do all types of formatting.

We use the prefix f in a string to format that string hence the name f-string. In fstring, we don’t need to apply any method to a string. Just by using f as a prefix, the formatting works. Let’s see fstring in action with some examples.

# Python f-string examples
language_name = 'Python'
print(f"I love {language_name} language")

Output:

I love Python language

We can do even arithmetic calculation inside a placeholder using a fstring.

x = 5
y = 8
print(f"x + y = {x+y} and x - y = {x-y}")

Output:

x + y = 13 and x - y = -3

Sharing is Caring

Leave a Comment

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