Image by Editor
If you’ve been using Python for a while, you’ll have likely stopped using the old-school format()
method to format strings. And switched to the more concise and easy-to-maintain f-Strings introduced in Python 3.6. But there is more.
Since Python 3.8 there are some nifty f-string features you can use for debugging, formatting datetime objects and floating point numbers, and much more. We’ll explore these use cases in this tutorial.
Note: To run the code examples you need to have Python 3.8 or a later version installed.
When you’re coding, you might use print()
statements to print out variables to verify if their values are what you expect them to be. With f-strings, you can include variable names and their values for easier debugging.
Consider the following example:
length = 4.5
breadth = 7.5
height = 9.0
print(f'{length=}, {breadth=}, {height=}')
This outputs:
Output >>> length=4.5, breadth=7.5, height=9.0
This feature is especially helpful when you want to understand the state of your variables during debugging. For production code, however, you should set up logging with the required log levels.
When printing out floating point numbers and datetime objects in Python, you’ll have to:
- Format floating point numbers to include a fixed number of digits after the decimal point
- Format dates in a particular consistent format
F-strings provide a straightforward way to format floats and dates according to your requirements.
In this example, you format the price
variable to display two places after the decimal point by specifying {price:.2f}
like so:
price = 1299.500
print(f'Price: ${price:.2f}')
Output >>> Price: $1299.50
You’d have used the strftime() method to format datetime objects in Python. But you can also do it with f-strings. Here’s an example:
from datetime import datetime
current_time = datetime.now()
print(f'Current date and time: {current_time:%Y-%m-%d %H:%M:%S}')
Output >>> Current date and time: 2023-10-12 15:25:08
Let’s code a simple example that include both date and float formatting:
price = 1299.500
purchase_date = datetime(2023, 10, 12, 15, 30)
print(f'Product purchased for ${price:.2f} on {purchase_date:%B %d, %Y at %H:%M}')
Output >>>
Product purchased for $1299.50 on October 12, 2023 at 15:30
F-strings support base conversion for numeric data types, allowing you to convert numbers from one base to another. So you don’t have to write separate base conversion functions or lambdas to view the number in a different base.
To print out the binary and hexadecimal equivalents of the decimal number 42 you can use f-string as shown:
num = 42
print(f'Decimal {num}, in binary: {num:b}, in hexadecimal: {num:x}')
Output >>>
Decimal 42, in binary: 101010, in hexadecimal: 2a
As seen, this is helpful when you need to print out numbers in different bases, like binary or hexadecimal. Let’s take another example for decimal to octal conversion:
num = 25
print(f'Decimal {num}, in octal: {num:o}')
Output >>> Decimal 25, in octal: 31
Remember Oct 31 = Dec 25? Yes, this example is inspired by “Why do developers confuse Halloween with Christmas?” memes.
You can use the !a and !r conversion flags within f-strings to format strings as ASCII and repr
strings, respectively.
Sometimes you may need to convert a string to its ASCII notation . Here is how you can do it using the !a flag:
emoji = "????"
print(f'ASCII representation of Emoji: {emoji!a}')
Output >>>
ASCII representation of Emoji: '\U0001f642'
To access the repr
of any object you can use f-strings with the !r flag:
from dataclasses import dataclass
@dataclass
class Point3D:
x: float = 0.0
y: float = 0.0
z: float = 0.0
point = Point3D(0.5, 2.5, 1.5)
print(f'Repr of 3D Point: {point!r}')
Python dataclasses come with the default implementation of __repr__
so we don’t have to explicitly write one.
Output >>>
Repr of 3D Point: Point3D(x=0.5, y=2.5, z=1.5)
When working with large language models like Llama and GPT-4, f-strings are helpful for creating prompt templates.
Instead of hardcoding prompt strings, you can create reusable and composable prompt templates using f-strings. You can then insert variables, questions, or context as needed.
If you’re using a framework like LangChain you can use the PromptTemplate features of the framework. But even if not, you can always use f-string-based prompt templates.
Prompts can be as simple as:
prompt_1 = "Give me the top 5 best selling books of Stephen King."
Or a slightly more flexible (but super simple still):
num = 5
author="Stephen King"
prompt_2 = f"Give me the top {num} best selling books of {author}."
In some cases it’s helpful to provide context and a few examples in your prompt.
Consider this example:
# context
user_context = "I'm planning to travel to Paris; I need some information."
# examples
few_shot_examples = [
{
"query": "What are some popular tourist attractions in Paris?",
"answer": "The Eiffel Tower, Louvre Museum, and Notre-Dame Cathedral are some popular attractions.",
},
{
"query": "What's the weather like in Paris in November?",
"answer": "In November, Paris experiences cool and damp weather with temperatures around 10-15°C.",
},
]
# question
user_question = "Can you recommend some good restaurants in Paris?"
Here’s a reusable prompt template using f-strings. Which you can use for any context, example, query use case:
# Constructing the Prompt using a multiline string
prompt = f'''
Context: {user_context}
Examples:
'''
for example in few_shot_examples:
prompt += f'''
Question: {example['query']}\nAnswer: {example['answer']}\n'''
prompt += f'''
Query: {user_question}
'''
print(prompt)
Here’s our prompt for this example:
Output >>>
Context: I'm planning to travel to Paris; I need some information.
Examples:
Question: What are some popular tourist attractions in Paris?
Answer: The Eiffel Tower, Louvre Museum, and Notre-Dame Cathedral are some popular attractions.
Question: What's the weather like in Paris in November?
Answer: In November, Paris experiences cool and damp weather with temperatures around 10-15°C.
Query: Can you recommend some good restaurants in Paris?
And that’s a wrap. I hope you found a few Python f-string features to add to your programmer’s toolbox. If you’re interested in learning Python, check out our compilation of 5 Free Books to Help You Master Python. Happy learning!
Bala Priya C is a developer and technical writer from India. She likes working at the intersection of math, programming, data science, and content creation. Her areas of interest and expertise include DevOps, data science, and natural language processing. She enjoys reading, writing, coding, and coffee! Currently, she’s working on learning and sharing her knowledge with the developer community by authoring tutorials, how-to guides, opinion pieces, and more.