Locked learning resources

Join us and get access to thousands of tutorials and a community of expert Pythonistas.

Unlock This Lesson

Locked learning resources

This lesson is for members only. Join us and get access to thousands of tutorials and a community of expert Pythonistas.

Unlock This Lesson

Multiline F-Strings

In this lesson, you’ll learn how to write f strings over multiple lines. You’ll see three different methods of spreading strings over multiple lines using the f-string “f” character, escaping returns, and using triple quotes (""").

00:00 With f-strings, you can do multiline f-strings also. Let me show you some examples.

00:12 Let’s assemble a multiline message here. I’ll have you open up a parentheses at the top. I’m leaving a space at the end of each string, at least these first two.

00:27 And finally, close the statement parentheses. So, what does message look like? Just remember, for each of these you do need to put the f at each one in order for it to render each of these expressions into the string.

00:46 If you were to create the message and miss some and say….

00:57 Close our parentheses. What would you get then? It will not be expressing these as f-strings, and so for these other two, these two expressions won’t be evaluated because the f-string is not at the front of it.

01:12 Another way that you can work with multiple lines is to escape them at the end of each line by using a backslash (\).

01:24 Once that’s entered in and you type message, you can see that it generates the same style as long as there’s a \ each at the end of each one of these, and they all have f at the beginning of the lines.

01:39 How about using triple quotes (""")? That works too!

01:54 So, how does that print out? In that circumstance, you will see all the line returns. A common use that I have for this, this triple quote style, is for creating SQL statements. For this SQL statement, we could have a couple of variables that we want to pull, so that might look like sql_statement, we’ll use our """ here, and I would make a SELECT. And let’s say it’s from a contact database, and this is the CONTACTS table. And in my WHERE statement, I want to use my expressions. I want to programmatically pull in the name. Also, I want to find the appropriate age to pull in the contact that I need. I’m ending my statement with a semi-colon, like all great SQL statements. And at the end here, I’ll put my """. So when I run my SQL query, it will plug in our data on the fly.

02:44 It’s very handy. SQL is nice because it ignores all the whitespace in the same way that HTML does, so it will ignore these returns. Next, let’s talk about speed.

Avatar image for gilpinbmchs

gilpinbmchs on April 16, 2020

I get an error after I hit <enter> when trying the ‘message = f”“”’

Avatar image for Ricky White

Ricky White RP Team on April 17, 2020

Hi @gilpinbmchs. What happens when you finish the string with the closing triple quotes?

Avatar image for anandxrfeu

anandxrfeu on May 26, 2020

Hello!

At 1:38 you show the syntax of escaping return with a . I dont get it. The syntax with and without ‘' seem identical. Could you please explain the ‘' use?

Avatar image for anandxrfeu

anandxrfeu on May 26, 2020

Hello!

At 1:38 you show the syntax of escaping return with a \. I dont get it. The syntax with and without \ seem identical. Could you please explain the \ use?

Avatar image for alvesmig

alvesmig on June 28, 2020

@ anandxrfeu Hi, the syntax without \ needs parenthesis. The one with \ don’t need parenthesis. That’s the difference between the two. I hope it would help Best regards Miguel Alves

Avatar image for alvesmig

alvesmig on June 28, 2020

Hi, why did you not explain this method? Is it bad practice?

message = f"Hi {name} \
You are a {profession} \
You were in {affiliation}"

By the way, I find the course very interesting and well taught. Best regards Miguel Alves

Avatar image for aquibmir

aquibmir on Dec. 6, 2021

The sql generated has \n, how is it usable in any program? You don’t provide any solution to that.

Avatar image for Bartosz Zaczyński

Bartosz Zaczyński RP Team on Dec. 6, 2021

@aquibmir All database management systems that I know of ignore whitespace in SQL queries, which lets you break lines at will. If you want to get rid of the trailing newline, then you can call str.rstrip(), which strips the whitespace on the right-hand side of the string. There’s a corresponding str.lstrip() method for the left-hand side and str.strip() for both sides:

>>> name = "Eric Idle"
>>> age = 74

>>> sql_statament = f"""
...     SELECT *
...     FROM contacts
...     WHERE name = '{name}' AND
...           age = '{age}';
... """

>>> sql_statament.strip()
"SELECT *\n    FROM contacts\n    WHERE name = 'Eric Idle' AND\n          age = '74';"

If you want to collapse the extra whitespace, then you can use a regular expression like so:

>>> import re
>>> re.sub(r"\s+", " ", sql_statament.strip())
"SELECT * FROM contacts WHERE name = 'Eric Idle' AND age = '74';"
Avatar image for mima

mima on Dec. 15, 2021

Hello. Isn’t using f-strings for SQL statements considered an antipattern because of SQL injection?

Avatar image for Bartosz Zaczyński

Bartosz Zaczyński RP Team on Dec. 15, 2021

@mima Absolutely. SQL queries that accept parameters from external sources such as users should always be made through prepared statements, which take care of illegal characters.

Become a Member to join the conversation.