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..28e9a40d23 --- /dev/null +++ b/python-f-string/basic_f_strings.py @@ -0,0 +1,6 @@ +name = "Jane" +age = 25 + +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 new file mode 100644 index 0000000000..3f631ef024 --- /dev/null +++ b/python-f-string/basic_format_method.py @@ -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)) diff --git a/python-f-string/basic_modulo.py b/python-f-string/basic_modulo.py new file mode 100644 index 0000000000..8b4e2892c2 --- /dev/null +++ b/python-f-string/basic_modulo.py @@ -0,0 +1,5 @@ +name = "Jane" +age = 25 + +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 new file mode 100644 index 0000000000..5654aff30d --- /dev/null +++ b/python-f-string/dictionaries.py @@ -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) 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..557dab115d --- /dev/null +++ b/python-f-string/f_strings_doc_expressions.py @@ -0,0 +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 new file mode 100644 index 0000000000..10f83760fb --- /dev/null +++ b/python-f-string/f_strings_expressions.py @@ -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)]}") diff --git a/python-f-string/f_strings_representation.py b/python-f-string/f_strings_representation.py new file mode 100644 index 0000000000..aa961be776 --- /dev/null +++ b/python-f-string/f_strings_representation.py @@ -0,0 +1,6 @@ +from person import Person + +jane = Person("Jane Doe", 25) + +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 new file mode 100644 index 0000000000..8565043894 --- /dev/null +++ b/python-f-string/format_f_string.py @@ -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]}") diff --git a/python-f-string/format_format_method.py b/python-f-string/format_format_method.py new file mode 100644 index 0000000000..a2ba099f3a --- /dev/null +++ b/python-f-string/format_format_method.py @@ -0,0 +1,3 @@ +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 new file mode 100644 index 0000000000..1eb61700c2 --- /dev/null +++ b/python-f-string/format_modulo.py @@ -0,0 +1,3 @@ +print("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..5862d1f01c --- /dev/null +++ b/python-f-string/logging_modulo.py @@ -0,0 +1,7 @@ +import logging + +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 new file mode 100644 index 0000000000..3b816b09d2 --- /dev/null +++ b/python-f-string/performance.py @@ -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) 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.") diff --git a/python-f-string/sql_queries.py b/python-f-string/sql_queries.py new file mode 100644 index 0000000000..c0f532a55b --- /dev/null +++ b/python-f-string/sql_queries.py @@ -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,))