Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Sample code for the article on f-strings #435

Merged
merged 9 commits into from
Oct 11, 2023
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
3 changes: 3 additions & 0 deletions python-f-string/README.md
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/).
6 changes: 6 additions & 0 deletions python-f-string/basic_f_strings.py
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}")
5 changes: 5 additions & 0 deletions python-f-string/basic_format_method.py
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))
5 changes: 5 additions & 0 deletions python-f-string/basic_modulo.py
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))
9 changes: 9 additions & 0 deletions python-f-string/dictionaries.py
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)
3 changes: 3 additions & 0 deletions python-f-string/f_strings_doc_expressions.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,3 @@
variable = "Some mysterious value"

print(f"{variable = }")
5 changes: 5 additions & 0 deletions python-f-string/f_strings_expressions.py
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)]}")
6 changes: 6 additions & 0 deletions python-f-string/f_strings_representation.py
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}")
18 changes: 18 additions & 0 deletions python-f-string/format_f_string.py
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]}")
3 changes: 3 additions & 0 deletions python-f-string/format_format_method.py
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"))
3 changes: 3 additions & 0 deletions python-f-string/format_modulo.py
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))
8 changes: 8 additions & 0 deletions python-f-string/i18n_format_method.py
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))
7 changes: 7 additions & 0 deletions python-f-string/logging_modulo.py
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")
19 changes: 19 additions & 0 deletions python-f-string/performance.py
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)
10 changes: 10 additions & 0 deletions python-f-string/person.py
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})"
4 changes: 4 additions & 0 deletions python-f-string/sample_v1.py
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))
4 changes: 4 additions & 0 deletions python-f-string/sample_v2.py
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.")
23 changes: 23 additions & 0 deletions python-f-string/sql_queries.py
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,))
Loading