Trusted answers to developer questions
Trusted Answers to Developer Questions

Related Tags

python
communitycreator

What are formatted strings in Python?

Onyejiaku Theophilus Chidalu

Overview

A formatted string is a type of string that is prefixed with an f and curly braces {} to dynamically insert values into your strings. Formatted strings are particularly useful in situations where you want to generate text with your variables. Formatted strings make it easier to visualize the output.

Code

# let say we have two variables
First_name = 'Theo'
Last_name = 'John'
# Now we want to generate an output like the one below on the terminal window
# Theo [John] is a coder
# Introducing a new variable
Output = First_name + ' [' + Last_name + '] is a coder '
print(Output)

How to use formatted strings

The approach in the program above is not ideal because as our text becomes more complicated, it becomes harder to visualize the string concatenations. Now, this is where formatted strings come in, as they make it a lot easier for you to visualize the output.

Code

# Introducing our variables like we did before
First_name = 'Theo'
Last_name = 'John'
# introducing the formatted string
Output = f'{First_name} [{Last_name}] is a coder'
print(Output)

In the program above, the use of a formatted string makes it easy to visualize the output. Now, let’s look at another example.

Name = 'Theophilus Onyejiaku'
Course_of_study = 'Bioresources Engineering'
School = 'Federal University of Technology, Owerri'
Output = f'{Name} studied {Course_of_study} at {School}'
print(Output)

The program above not only demonstrates how easy it is for one to visualize the output but also how to easily generate text outputs with your variables.

Multi-line formatted strings

Imagine a situation where you need to write multiple lines of formatted strings. The program below shows how to easily write multiple lines of formatted strings that contain expressions.

Code

# introducing arithmetic expressions 
x = 20
y = 10
add = x + y
minus = x - y
multiply = x * y
# using multiline formatted string
output = f'The summation of x and y is {add}. ' \
f'The subtraction of y from x is {minus}. ' \
f'The multiplication of x by y is {multiply}. '
print(output)

In the code above, we demonstrate that you need to put an f in front of each of the lines of string when you write multiple lines of formatted strings. To expand the strings over multiple lines and to escape a return, you use the backslash \.

RELATED TAGS

python
communitycreator

CONTRIBUTOR

Onyejiaku Theophilus Chidalu
RELATED COURSES

View all Courses

Keep Exploring