Trusted answers to developer questions
Trusted Answers to Developer Questions

Related Tags

formatting
string
f-strings
python

How to use f-strings in Python

Ammar Ahmad Farid

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)
Using the "%" operator

  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)
Calling the format() function

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)
Using f-string

RELATED TAGS

formatting
string
f-strings
python

CONTRIBUTOR

Ammar Ahmad Farid
Copyright ©2022 Educative, Inc. All rights reserved
RELATED COURSES

View all Courses

Keep Exploring