-
Notifications
You must be signed in to change notification settings - Fork 5.3k
Commit
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
Merge pull request #435 from realpython/python-f-string
Sample code for the article on f-strings
- Loading branch information
Showing
18 changed files
with
141 additions
and
0 deletions.
There are no files selected for viewing
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,3 @@ | ||
# Python's F-String: An Improved String Interpolation and Formatting Tool | ||
|
||
This folder provides the code examples for the Real Python tutorial [Python's F-String: An Improved String Interpolation and Formatting Tool](https://realpython.com/python-f-string-update/). |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,6 @@ | ||
name = "Jane" | ||
age = 25 | ||
|
||
print(f"Hello, {name}! You're {age} years old.") | ||
|
||
print(f"{2 * 21}") |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,5 @@ | ||
name = "Jane" | ||
age = 25 | ||
|
||
print("Hello, {}! You're {} years old.".format(name, age)) | ||
print("Hello, {name}! You're {age} years old.".format(name="Jane", age=25)) |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,5 @@ | ||
name = "Jane" | ||
age = 25 | ||
|
||
print("Hello, %s!" % name) | ||
print("Hello, %s! You're %s years old." % (name, age)) |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,9 @@ | ||
person = {"name": "Jane Doe", "age": 25} | ||
|
||
print(f"Hello, {person['name']}! You're {person['age']} years old.") | ||
|
||
print("Hello, {name}! You're {age} years old.".format(**person)) | ||
print("Hello, {name}!".format(**person)) | ||
|
||
print("Hello, %(name)s! You're %(age)s years old." % person) | ||
print("Hello, %(name)s!" % person) |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,3 @@ | ||
variable = "Some mysterious value" | ||
|
||
print(f"{variable = }") |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,5 @@ | ||
name = "Jane" | ||
age = 25 | ||
|
||
print(f"Hello, {name.upper()}! You're {age} years old.") | ||
print(f"{[2**n for n in range(3, 9)]}") |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,6 @@ | ||
from person import Person | ||
|
||
jane = Person("Jane Doe", 25) | ||
|
||
print(f"{jane!s}") | ||
print(f"{jane!r}") |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,18 @@ | ||
balance = 5425.9292 | ||
print(f"Balance: ${balance:.2f}") | ||
|
||
heading = "Centered string" | ||
print(f"{heading:=^30}") | ||
|
||
integer = -1234567 | ||
print(f"Comma as thousand separators: {integer:,}") | ||
sep = "_" | ||
print(f"User's thousand separators: {integer:{sep}}") | ||
|
||
floating_point = 1234567.9876 | ||
print(f"Comma as thousand separators and two decimals: {floating_point:,.2f}") | ||
|
||
date = (9, 6, 2023) | ||
print(f"Date: {date[0]:02}-{date[1]:02}-{date[2]}") | ||
date = (9, 26, 2023) | ||
print(f"Date: {date[0]:02}/{date[1]:02}/{date[2]}") |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,3 @@ | ||
print("Balance: ${:.2f}".format(5425.9292)) | ||
|
||
print("{:=^30}".format("Centered string")) |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,3 @@ | ||
print("Balance: $%.2f" % 5425.9292) | ||
|
||
print("Name: %s\nAge: %5s" % ("John", 35)) |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,8 @@ | ||
greeting_template = "{greeting} Pythonista!" | ||
|
||
greeting_en = "Good Morning!" | ||
greeting_es = "¡Buenos días!" | ||
greeting_fr = "Bonjour!" | ||
|
||
for greeting in (greeting_en, greeting_es, greeting_fr): | ||
print(greeting_template.format(greeting=greeting)) |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,7 @@ | ||
import logging | ||
|
||
msg = "This is a %s message!" | ||
|
||
logging.warning(msg, "WARNING") | ||
|
||
logging.debug(msg, "DEBUGGING") |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,19 @@ | ||
import timeit | ||
|
||
name = "Linda Smith" | ||
age = 40 | ||
strings = { | ||
"Modulo operator": "'Name: %s Age: %s' % (name, age)", | ||
".format() method": "'Name: {} Age: {}'.format(name, age)", | ||
"f_string": "f'Name: {name} Age: {age}'", | ||
} | ||
|
||
|
||
def run_performance_test(strings): | ||
max_length = len(max(strings, key=len)) | ||
for tool, string in strings.items(): | ||
time = timeit.timeit(string, number=1000000, globals=globals()) * 1000 | ||
print(f"{tool}: {time:>{max_length - len(tool) + 6}.2f} ms") | ||
|
||
|
||
run_performance_test(strings) |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,10 @@ | ||
class Person: | ||
def __init__(self, name, age): | ||
self.name = name | ||
self.age = age | ||
|
||
def __str__(self): | ||
return f"I'm {self.name}, and I'm {self.age} years old." | ||
|
||
def __repr__(self): | ||
return f"{type(self).__name__}(name='{self.name}', age={self.age})" |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,4 @@ | ||
name = "Jane" | ||
age = 25 | ||
|
||
print("Hello, %s! You're %s years old." % (name, age)) |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,4 @@ | ||
name = "Jane" | ||
age = 25 | ||
|
||
print(f"Hello, {name}! You're {age} years old.") |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,23 @@ | ||
import psycopg2 | ||
|
||
# This code doesn't run because of the missing `psycopg2` library | ||
# and the assumption of a certain database structure and setup. | ||
# It's a demonstrative code only. | ||
|
||
connection = psycopg2.connect(database="db", user="user", password="password") | ||
cursor = connection.cursor() | ||
|
||
role = "admin" | ||
|
||
query_modulo = "SELECT * FROM users WHERE role = '%s'" % role | ||
query_format = "SELECT * FROM users WHERE role = '{role}'".format(role=role) | ||
query_f_string = f"SELECT * FROM users WHERE role = '{role}'" | ||
|
||
cursor.execute(query_modulo) | ||
cursor.execute(query_format) | ||
cursor.execute(query_f_string) | ||
|
||
# Correct query | ||
query_template = "SELECT * FROM users WHERE role = %s" | ||
|
||
cursor.execute(query_template, (role,)) |