If you have been using Python for a while, you have probably 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. However, there are some additional features in f-Strings that you can use for debugging, formatting datetime objects and floating point numbers, and more since Python 3.8. In this tutorial, we will explore these use cases.
Note: To run the code examples, you need to have Python 3.8 or a later version installed.
When coding, you might use print() statements to print out variables to verify their values. With f-Strings, you can include variable names and their values for easier debugging. Here is an example:
“`python
length = 4.5
breadth = 7.5
height = 9.0
print(f'{length=}, {breadth=}, {height=}’)
“`
This will output:
“`
length=4.5, breadth=7.5, height=9.0
“`
This feature is especially helpful for understanding the state of your variables during debugging. However, for production code, it is recommended to set up logging with the required log levels.
When printing floating point numbers and datetime objects in Python, you will often need to format them in a specific way. F-Strings provide a straightforward way to format floats and dates according to your requirements. Here are some examples:
“`python
price = 1299.500
print(f’Price: ${price:.2f}’)
current_time = datetime.now()
print(f’Current date and time: {current_time:%Y-%m-%d %H:%M:%S}’)
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}’)
“`
F-Strings also support base conversion for numeric data types. This allows you to easily convert numbers from one base to another. For example:
“`python
num = 42
print(f’Decimal {num}, in binary: {num:b}, in hexadecimal: {num:x}’)
num = 25
print(f’Decimal {num}, in octal: {num:o}’)
“`
You can use the !a and !r conversion flags within f-Strings to format strings as ASCII and repr strings, respectively. For example:
“`python
emoji = “🙂”
print(f’ASCII representation of Emoji: {emoji!a}’)
point = Point3D(0.5, 2.5, 1.5)
print(f’Repr of 3D Point: {point!r}’)
“`
F-Strings are also helpful for creating prompt templates when working with large language models. Instead of hardcoding prompt strings, you can create reusable and composable prompt templates using f-Strings. Here are some examples:
“`python
prompt_1 = “Give me the top 5 best selling books of Stephen King.”
num = 5
author = “Stephen King”
prompt_2 = f”Give me the top {num} best selling books of {author}.”
user_context = “I’m planning to travel to Paris; I need some information.”
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.”,
},
]
user_question = “Can you recommend some good restaurants in Paris?”
prompt = f”’
Context: {user_context}
Examples:
”’
for example in few_shot_examples:
prompt += f”’
Question: {example[‘query’]}
Answer: {example[‘answer’]}
”’
prompt += f”’
Query: {user_question}
”’
print(prompt)
“`
That’s it! I hope you found these Python f-String features useful for your programming tasks. If you are interested in learning more about 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 enjoys 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 is currently focused on learning and sharing her knowledge with the developer community through tutorials, how-to guides, opinion pieces, and more.
Source link