Editor’s Image
If you’ve been using Python for a while, you’ve probably grown old school. format()
Method for formatting strings. And I switched to the more concise and maintainable f-Strings. introduced in Python 3.6. But there is more.
Since Python 3.8, there are some nifty f-string functions you can use for debugging, formatting datetime objects and floating-point numbers, and much more. We will explore these use cases in this tutorial.
Note: To run the code examples you need to have Python 3.8 or later installed.
When you are coding, you can use print()
statements to print variables and check if their values are what you expect them to be. With f-strings, you can include variable names and their values to facilitate debugging.
Consider the following example:
length = 4.5
breadth = 7.5
height = 9.0
print(f'{length=}, {breadth=}, {height=}')
This produces:
Output >>> length=4.5, breadth=7.5, height=9.0
This feature is especially useful when you want to understand the state of your variables while debugging. However, for production code, you must configure logging with the required logging levels.
When printing floating point numbers and datetime objects in Python, you will need 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 simple way to format floats and dates according to your requirements.
In this example, format the price
variable to display two places after the decimal point by specifying {price:.2f}
like:
price = 1299.500
print(f'Price: ${price:.2f}')
Output >>> Price: $1299.50
You would have used the execution time() Method to format date and time objects in Python. But you can also do it with f strings. Here is 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 includes date formatting and float:
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. Therefore, there is no need to write separate base conversion functions or lambdas to view the number in a different base.
To print 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 you can see, this is useful when you need to print numbers in different bases, such as binary or hexadecimal. Let’s take another example of decimal to octal conversion:
num = 25
print(f'Decimal {num}, in octal: {num:o}')
Output >>> Decimal 25, in octal: 31
Remember October 31 = December 25? Yes, this example is inspired by “Why do developers confuse Halloween with Christmas?” memes.
You can use the !to and !r conversion flags inside f-strings to format strings as ASCII and repr
strings, respectively.
Sometimes you may need to convert a string to its ASCII notation. This is how you can do it using the !to 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 data classes come with the default implementation of __repr__
so we don’t have to write one explicitly.
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 useful for creating message templates.
Instead of encoding message strings, you can create rusable and composable message templates using strings f. You can then insert variables, questions or context as needed.
If you are using a framework like LangChain, you can use the Notice template frame features. But even if not, you can always use message templates based on f-strings.
Indications can be as simple as:
prompt_1 = "Give me the top 5 best selling books of Stephen King."
Or a little more flexible (but still super simple):
num = 5
author="Stephen King"
prompt_2 = f"Give me the top {num} best selling books of {author}."
In some cases, it is helpful to provide context and some examples in the message.
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 is a reusable prompt template that uses 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 is our message 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’ve found some Python f-string features to add to your programmer’s toolbox. If you are interested in learning Python, check out our collection of 5 free books to help you master Python. Happy learning!
Bala Priya C. is a developer and technical writer from India. He enjoys working at the intersection of mathematics, programming, data science, and content creation. His areas of interest and expertise include DevOps, data science, and natural language processing. He likes to read, write, code and drink coffee! Currently, he is working to learn and share his knowledge with the developer community by creating tutorials, how-to guides, opinion pieces, and more.