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 2 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/).
5 changes: 5 additions & 0 deletions python-f-string/basic_f_strings.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,5 @@
name = "Jane"
age = 25
f"Hello, {name}! You're {age} years old."

f"{2 * 21}"
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I think that for providing these code blocks as files it makes sense to wrap REPL session output into calls to print(). That's at least what I've been doing, to make it convenient for readers to run.

Do we have a guideline on doing/not doing that @gahjelle ?

Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I guess that wrapping the code in calls to print() can confuse the reader because the code differs from the code in the article.

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

"Hello, {}! You're {} years old.".format(name, age)
"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

"Hello, %s!" % name
"Hello, %s! You're %s years old." % (name, age)
8 changes: 8 additions & 0 deletions python-f-string/dictionaries.py
Original file line number Diff line number Diff line change
@@ -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
2 changes: 2 additions & 0 deletions python-f-string/f_strings_doc_expressions.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,2 @@
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

f"Hello, {name.upper()}! You're {age} years old."
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)

f"{jane!s}"
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
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]}"
2 changes: 2 additions & 0 deletions python-f-string/format_format_method.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,2 @@
"Balance: ${:.2f}".format(5425.9292)
"{:=^30}".format("Centered string")
2 changes: 2 additions & 0 deletions python-f-string/format_modulo.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,2 @@
"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))
4 changes: 4 additions & 0 deletions python-f-string/logging_modulo.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,4 @@
import logging

msg_template = "Hey %s! You're using logging!"
logging.warning(msg_template, "Pythonista")
16 changes: 16 additions & 0 deletions python-f-string/performance.py
Original file line number Diff line number Diff line change
@@ -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")
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.")