From e23a5fcf0491eab38c61a1e942f007340e7e1c07 Mon Sep 17 00:00:00 2001 From: Leodanis Pozo Ramos Date: Tue, 12 Sep 2023 17:41:40 +0200 Subject: [PATCH 1/5] Sample code for the article on f-strings --- python-f-string/README.md | 3 +++ python-f-string/basic_f_strings.py | 5 +++++ python-f-string/basic_format_method.py | 5 +++++ python-f-string/basic_modulo.py | 5 +++++ python-f-string/dictionaries.py | 8 ++++++++ python-f-string/f_strings_doc_expressions.py | 2 ++ python-f-string/f_strings_expressions.py | 5 +++++ python-f-string/f_strings_representation.py | 6 ++++++ python-f-string/format_f_string.py | 18 ++++++++++++++++++ python-f-string/format_format_method.py | 2 ++ python-f-string/format_modulo.py | 2 ++ python-f-string/i18n_format_method.py | 8 ++++++++ python-f-string/logging_modulo.py | 3 +++ python-f-string/performance.py | 16 ++++++++++++++++ python-f-string/person.py | 10 ++++++++++ python-f-string/sample_v1.py | 4 ++++ python-f-string/sample_v2.py | 4 ++++ 17 files changed, 106 insertions(+) create mode 100644 python-f-string/README.md create mode 100644 python-f-string/basic_f_strings.py create mode 100644 python-f-string/basic_format_method.py create mode 100644 python-f-string/basic_modulo.py create mode 100644 python-f-string/dictionaries.py create mode 100644 python-f-string/f_strings_doc_expressions.py create mode 100644 python-f-string/f_strings_expressions.py create mode 100644 python-f-string/f_strings_representation.py create mode 100644 python-f-string/format_f_string.py create mode 100644 python-f-string/format_format_method.py create mode 100644 python-f-string/format_modulo.py create mode 100644 python-f-string/i18n_format_method.py create mode 100644 python-f-string/logging_modulo.py create mode 100644 python-f-string/performance.py create mode 100644 python-f-string/person.py create mode 100644 python-f-string/sample_v1.py create mode 100644 python-f-string/sample_v2.py diff --git a/python-f-string/README.md b/python-f-string/README.md new file mode 100644 index 0000000000..f143470e46 --- /dev/null +++ b/python-f-string/README.md @@ -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/). \ No newline at end of file diff --git a/python-f-string/basic_f_strings.py b/python-f-string/basic_f_strings.py new file mode 100644 index 0000000000..190ae4f1d0 --- /dev/null +++ b/python-f-string/basic_f_strings.py @@ -0,0 +1,5 @@ +name = "Jane" +age = 25 +f"Hello, {name}! You're {age} years old." + +f"{2 * 21}" diff --git a/python-f-string/basic_format_method.py b/python-f-string/basic_format_method.py new file mode 100644 index 0000000000..5db1f64528 --- /dev/null +++ b/python-f-string/basic_format_method.py @@ -0,0 +1,5 @@ +name = "Jane" +age = 25 + +"Hello, {}! You're {} years old.".format(name, age) +"Hello, {name}! You're {age} years old.".format(name="Jane", age=25) diff --git a/python-f-string/basic_modulo.py b/python-f-string/basic_modulo.py new file mode 100644 index 0000000000..2e4fa1e417 --- /dev/null +++ b/python-f-string/basic_modulo.py @@ -0,0 +1,5 @@ +name = "Jane" +age = 25 + +"Hello, %s!" % name +"Hello, %s! You're %s years old." % (name, age) diff --git a/python-f-string/dictionaries.py b/python-f-string/dictionaries.py new file mode 100644 index 0000000000..2130075dc2 --- /dev/null +++ b/python-f-string/dictionaries.py @@ -0,0 +1,8 @@ +person = {"name": "Jane Doe", "age": 25} +f"Hello, {person['name']}! You're {person['age']} years old." + +"Hello, {name}! You're {age} years old.".format(**person) +"Hello, {name}!".format(**person) + +"Hello, %(name)s! You're %(age)s years old." % person +"Hello, %(name)s!" % person diff --git a/python-f-string/f_strings_doc_expressions.py b/python-f-string/f_strings_doc_expressions.py new file mode 100644 index 0000000000..bfce013342 --- /dev/null +++ b/python-f-string/f_strings_doc_expressions.py @@ -0,0 +1,2 @@ +variable = "Some mysterious value" +print(f"{variable = }") diff --git a/python-f-string/f_strings_expressions.py b/python-f-string/f_strings_expressions.py new file mode 100644 index 0000000000..6529bd0974 --- /dev/null +++ b/python-f-string/f_strings_expressions.py @@ -0,0 +1,5 @@ +name = "Jane" +age = 25 + +f"Hello, {name.upper()}! You're {age} years old." +f"{[2**n for n in range(3, 9)]}" diff --git a/python-f-string/f_strings_representation.py b/python-f-string/f_strings_representation.py new file mode 100644 index 0000000000..c58f37f8dd --- /dev/null +++ b/python-f-string/f_strings_representation.py @@ -0,0 +1,6 @@ +from person import Person + +jane = Person("Jane Doe", 25) + +f"{jane!s}" +f"{jane!r}" diff --git a/python-f-string/format_f_string.py b/python-f-string/format_f_string.py new file mode 100644 index 0000000000..282b4f61f5 --- /dev/null +++ b/python-f-string/format_f_string.py @@ -0,0 +1,18 @@ +balance = 5425.9292 +f"Balance: ${balance:.2f}" + +heading = "Centered string" +f"{heading:=^30}" + +integer = -1234567 +f"Comma as thousand separators: {integer:,}" +sep = "_" +f"User's thousand separators: {integer:{sep}}" + +floating_point = 1234567.9876 +f"Comma as thousand separator: {floating_point:,.2f}" + +date = (9, 6, 2023) +f"Date: {date[0]:02}-{date[1]:02}-{date[2]}" +date = (9, 26, 2023) +f"Date: {date[0]:02}/{date[1]:02}/{date[2]}" diff --git a/python-f-string/format_format_method.py b/python-f-string/format_format_method.py new file mode 100644 index 0000000000..995ee4fe9f --- /dev/null +++ b/python-f-string/format_format_method.py @@ -0,0 +1,2 @@ +"Balance: ${:.2f}".format(5425.9292) +"{:=^30}".format("Centered string") diff --git a/python-f-string/format_modulo.py b/python-f-string/format_modulo.py new file mode 100644 index 0000000000..91cae96a2e --- /dev/null +++ b/python-f-string/format_modulo.py @@ -0,0 +1,2 @@ +"Balance: $%.2f" % 5425.9292 +print("Name: %s\nAge: %5s" % ("John", 35)) diff --git a/python-f-string/i18n_format_method.py b/python-f-string/i18n_format_method.py new file mode 100644 index 0000000000..bc9655f362 --- /dev/null +++ b/python-f-string/i18n_format_method.py @@ -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)) diff --git a/python-f-string/logging_modulo.py b/python-f-string/logging_modulo.py new file mode 100644 index 0000000000..9e59753894 --- /dev/null +++ b/python-f-string/logging_modulo.py @@ -0,0 +1,3 @@ +import logging +msg_template = "Hey %s! You're using logging!" +logging.warning(msg_template, "Pythonista") diff --git a/python-f-string/performance.py b/python-f-string/performance.py new file mode 100644 index 0000000000..3b52341c35 --- /dev/null +++ b/python-f-string/performance.py @@ -0,0 +1,16 @@ +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") diff --git a/python-f-string/person.py b/python-f-string/person.py new file mode 100644 index 0000000000..65769d3e5f --- /dev/null +++ b/python-f-string/person.py @@ -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})" diff --git a/python-f-string/sample_v1.py b/python-f-string/sample_v1.py new file mode 100644 index 0000000000..18dbeb738c --- /dev/null +++ b/python-f-string/sample_v1.py @@ -0,0 +1,4 @@ +name = "Jane" +age = 25 + +print("Hello, %s! You're %s years old." % (name, age)) diff --git a/python-f-string/sample_v2.py b/python-f-string/sample_v2.py new file mode 100644 index 0000000000..0747e3b0e6 --- /dev/null +++ b/python-f-string/sample_v2.py @@ -0,0 +1,4 @@ +name = "Jane" +age = 25 + +print(f"Hello, {name}! You're {age} years old.") From 4f0099cebcc87b2a4300ed628f81171359216676 Mon Sep 17 00:00:00 2001 From: Leodanis Pozo Ramos Date: Tue, 12 Sep 2023 17:44:22 +0200 Subject: [PATCH 2/5] Fix linter issues --- python-f-string/logging_modulo.py | 1 + 1 file changed, 1 insertion(+) diff --git a/python-f-string/logging_modulo.py b/python-f-string/logging_modulo.py index 9e59753894..cca39f8b3e 100644 --- a/python-f-string/logging_modulo.py +++ b/python-f-string/logging_modulo.py @@ -1,3 +1,4 @@ import logging + msg_template = "Hey %s! You're using logging!" logging.warning(msg_template, "Pythonista") From b7ffcc5dddda2b50e84dc20adda7b8566676a4b9 Mon Sep 17 00:00:00 2001 From: Leodanis Pozo Ramos Date: Wed, 27 Sep 2023 09:08:47 +0200 Subject: [PATCH 3/5] TR updates --- python-f-string/basic_f_strings.py | 5 +++-- python-f-string/basic_format_method.py | 4 ++-- python-f-string/basic_modulo.py | 4 ++-- python-f-string/dictionaries.py | 11 ++++++----- python-f-string/f_strings_doc_expressions.py | 1 + python-f-string/f_strings_expressions.py | 4 ++-- python-f-string/f_strings_representation.py | 4 ++-- python-f-string/format_f_string.py | 14 +++++++------- python-f-string/format_format_method.py | 5 +++-- python-f-string/format_modulo.py | 3 ++- python-f-string/logging_modulo.py | 7 +++++-- python-f-string/performance.py | 3 +++ python-f-string/sql_queries.py | 19 +++++++++++++++++++ 13 files changed, 57 insertions(+), 27 deletions(-) create mode 100644 python-f-string/sql_queries.py diff --git a/python-f-string/basic_f_strings.py b/python-f-string/basic_f_strings.py index 190ae4f1d0..28e9a40d23 100644 --- a/python-f-string/basic_f_strings.py +++ b/python-f-string/basic_f_strings.py @@ -1,5 +1,6 @@ name = "Jane" age = 25 -f"Hello, {name}! You're {age} years old." -f"{2 * 21}" +print(f"Hello, {name}! You're {age} years old.") + +print(f"{2 * 21}") diff --git a/python-f-string/basic_format_method.py b/python-f-string/basic_format_method.py index 5db1f64528..3f631ef024 100644 --- a/python-f-string/basic_format_method.py +++ b/python-f-string/basic_format_method.py @@ -1,5 +1,5 @@ name = "Jane" age = 25 -"Hello, {}! You're {} years old.".format(name, age) -"Hello, {name}! You're {age} years old.".format(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)) diff --git a/python-f-string/basic_modulo.py b/python-f-string/basic_modulo.py index 2e4fa1e417..8b4e2892c2 100644 --- a/python-f-string/basic_modulo.py +++ b/python-f-string/basic_modulo.py @@ -1,5 +1,5 @@ name = "Jane" age = 25 -"Hello, %s!" % name -"Hello, %s! You're %s years old." % (name, age) +print("Hello, %s!" % name) +print("Hello, %s! You're %s years old." % (name, age)) diff --git a/python-f-string/dictionaries.py b/python-f-string/dictionaries.py index 2130075dc2..5654aff30d 100644 --- a/python-f-string/dictionaries.py +++ b/python-f-string/dictionaries.py @@ -1,8 +1,9 @@ person = {"name": "Jane Doe", "age": 25} -f"Hello, {person['name']}! You're {person['age']} years old." -"Hello, {name}! You're {age} years old.".format(**person) -"Hello, {name}!".format(**person) +print(f"Hello, {person['name']}! You're {person['age']} years old.") -"Hello, %(name)s! You're %(age)s years old." % person -"Hello, %(name)s!" % person +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) diff --git a/python-f-string/f_strings_doc_expressions.py b/python-f-string/f_strings_doc_expressions.py index bfce013342..557dab115d 100644 --- a/python-f-string/f_strings_doc_expressions.py +++ b/python-f-string/f_strings_doc_expressions.py @@ -1,2 +1,3 @@ variable = "Some mysterious value" + print(f"{variable = }") diff --git a/python-f-string/f_strings_expressions.py b/python-f-string/f_strings_expressions.py index 6529bd0974..10f83760fb 100644 --- a/python-f-string/f_strings_expressions.py +++ b/python-f-string/f_strings_expressions.py @@ -1,5 +1,5 @@ name = "Jane" age = 25 -f"Hello, {name.upper()}! You're {age} years old." -f"{[2**n for n in range(3, 9)]}" +print(f"Hello, {name.upper()}! You're {age} years old.") +print(f"{[2**n for n in range(3, 9)]}") diff --git a/python-f-string/f_strings_representation.py b/python-f-string/f_strings_representation.py index c58f37f8dd..aa961be776 100644 --- a/python-f-string/f_strings_representation.py +++ b/python-f-string/f_strings_representation.py @@ -2,5 +2,5 @@ jane = Person("Jane Doe", 25) -f"{jane!s}" -f"{jane!r}" +print(f"{jane!s}") +print(f"{jane!r}") diff --git a/python-f-string/format_f_string.py b/python-f-string/format_f_string.py index 282b4f61f5..0bfb01c6ad 100644 --- a/python-f-string/format_f_string.py +++ b/python-f-string/format_f_string.py @@ -1,18 +1,18 @@ balance = 5425.9292 -f"Balance: ${balance:.2f}" +print(f"Balance: ${balance:.2f}") heading = "Centered string" -f"{heading:=^30}" +print(f"{heading:=^30}") integer = -1234567 -f"Comma as thousand separators: {integer:,}" +print(f"Comma as thousand separators: {integer:,}") sep = "_" -f"User's thousand separators: {integer:{sep}}" +print(f"User's thousand separators: {integer:{sep}}") floating_point = 1234567.9876 -f"Comma as thousand separator: {floating_point:,.2f}" +print(f"Comma as thousand separator: {floating_point:,.2f}") date = (9, 6, 2023) -f"Date: {date[0]:02}-{date[1]:02}-{date[2]}" +print(f"Date: {date[0]:02}-{date[1]:02}-{date[2]}") date = (9, 26, 2023) -f"Date: {date[0]:02}/{date[1]:02}/{date[2]}" +print(f"Date: {date[0]:02}/{date[1]:02}/{date[2]}") diff --git a/python-f-string/format_format_method.py b/python-f-string/format_format_method.py index 995ee4fe9f..a2ba099f3a 100644 --- a/python-f-string/format_format_method.py +++ b/python-f-string/format_format_method.py @@ -1,2 +1,3 @@ -"Balance: ${:.2f}".format(5425.9292) -"{:=^30}".format("Centered string") +print("Balance: ${:.2f}".format(5425.9292)) + +print("{:=^30}".format("Centered string")) diff --git a/python-f-string/format_modulo.py b/python-f-string/format_modulo.py index 91cae96a2e..1eb61700c2 100644 --- a/python-f-string/format_modulo.py +++ b/python-f-string/format_modulo.py @@ -1,2 +1,3 @@ -"Balance: $%.2f" % 5425.9292 +print("Balance: $%.2f" % 5425.9292) + print("Name: %s\nAge: %5s" % ("John", 35)) diff --git a/python-f-string/logging_modulo.py b/python-f-string/logging_modulo.py index cca39f8b3e..5862d1f01c 100644 --- a/python-f-string/logging_modulo.py +++ b/python-f-string/logging_modulo.py @@ -1,4 +1,7 @@ import logging -msg_template = "Hey %s! You're using logging!" -logging.warning(msg_template, "Pythonista") +msg = "This is a %s message!" + +logging.warning(msg, "WARNING") + +logging.debug(msg, "DEBUGGING") diff --git a/python-f-string/performance.py b/python-f-string/performance.py index 3b52341c35..3b816b09d2 100644 --- a/python-f-string/performance.py +++ b/python-f-string/performance.py @@ -14,3 +14,6 @@ def run_performance_test(strings): 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) diff --git a/python-f-string/sql_queries.py b/python-f-string/sql_queries.py new file mode 100644 index 0000000000..0a1b7d8b9e --- /dev/null +++ b/python-f-string/sql_queries.py @@ -0,0 +1,19 @@ +import psycopg2 + +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,)) From 89a7851622477ba84c03892cf963394461908536 Mon Sep 17 00:00:00 2001 From: martin-martin Date: Wed, 27 Sep 2023 10:35:11 +0200 Subject: [PATCH 4/5] Update print text --- python-f-string/format_f_string.py | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/python-f-string/format_f_string.py b/python-f-string/format_f_string.py index 0bfb01c6ad..8565043894 100644 --- a/python-f-string/format_f_string.py +++ b/python-f-string/format_f_string.py @@ -10,7 +10,7 @@ print(f"User's thousand separators: {integer:{sep}}") floating_point = 1234567.9876 -print(f"Comma as thousand separator: {floating_point:,.2f}") +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]}") From 7443abdaf19b871255c9a0e616c4bff490c8f115 Mon Sep 17 00:00:00 2001 From: Leodanis Pozo Ramos Date: Wed, 27 Sep 2023 11:57:00 +0200 Subject: [PATCH 5/5] TR updates, second round --- python-f-string/sql_queries.py | 4 ++++ 1 file changed, 4 insertions(+) diff --git a/python-f-string/sql_queries.py b/python-f-string/sql_queries.py index 0a1b7d8b9e..c0f532a55b 100644 --- a/python-f-string/sql_queries.py +++ b/python-f-string/sql_queries.py @@ -1,5 +1,9 @@ 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()