How to use f-strings in Python

Overview

There are multiple ways to format strings in Python:

  1. %-formatting:

We can use the % operator to format the string objects shown below:

word = "World!"
print("Hello, %s." % word)

Let’s try this formatting:

name = "Marry"
print("Hello, %s." % name)

  1. str.format():

We can also call the built-in string format() function for formatting strings like this:

word = "World!"
string = "Hello, {}.".format(word)
print(string)

Let’s try it.

name = "Marry!"
string = "Hello, {}.".format(name)
print(string)

Note: Both of the options given above are readable, but our code will become less legible and messy when we use longer strings. Another option is to format the f-strings in Python.

f-strings

"Formatted string literals" are the string literals in which we use an f at the beginning and curly braces {} to enclose the expressions that will be replaced with other values.

Syntax

word = "World!"
fstring = f"Hello, {word}."

Let’s try out this type of formatting:

name = "Marry"
age = 18
fstring = f"Hello, {name}. Are you {age} years old?"
print(fstring)

Copyright ©2024 Educative, Inc. All rights reserved