Python f-Strings Magic: 5 Recreation-Altering Methods Each Coder Must Know


Python f-Strings Magic: 5 Game-Changing Tricks Every Coder Needs to Know
Picture by Editor

 

In the event you’ve been utilizing Python for some time, you’ll have doubtless stopped utilizing the old-school format() methodology to format strings. And switched to the extra concise and easy-to-maintain f-Strings introduced in Python 3.6. However there’s extra.

Since Python 3.8 there are some nifty f-string options you need to use for debugging, formatting datetime objects and floating level numbers, and far more. We’ll discover these use circumstances on this tutorial. 

 

Notice: To run the code examples it is advisable have Python 3.8 or a later model put in.

 

 

While you’re coding, you would possibly use print() statements to print out variables to confirm if their values are what you anticipate them to be. With f-strings, you may embody variable names and their values for simpler debugging.

Think about the next instance:

size = 4.5
breadth = 7.5
peak = 9.0

print(f'{size=}, {breadth=}, {peak=}')

 

This outputs:

Output >>> size=4.5, breadth=7.5, peak=9.0

 

This function is very useful while you wish to perceive the state of your variables throughout debugging. For manufacturing code, nevertheless, it is best to arrange logging with the required log ranges.

 

 

When printing out floating level numbers and datetime objects in Python, you’ll need to:

  • Format floating level numbers to incorporate a set variety of digits after the decimal level
  • Format dates in a specific constant format

F-strings present a simple method to format floats and dates in line with your necessities.

On this instance, you format the value variable to show two locations after the decimal level by specifying {value:.2f} like so:

value = 1299.500
print(f'Value: ${value:.2f}')

 

Output >>> Value: $1299.50

 

You’d have used the strftime() methodology to format datetime objects in Python. However you may as well do it with f-strings. Right here’s an instance:

from datetime import datetime
current_time = datetime.now()
print(f'Present date and time: {current_time:%Y-%m-%d %H:%M:%S}')

 

Output >>> Present date and time: 2023-10-12 15:25:08

 

Let’s code a easy instance that embody each date and float formatting:

value = 1299.500
purchase_date = datetime(2023, 10, 12, 15, 30)
print(f'Product bought for ${value:.2f} on {purchase_date:%B %d, %Y at %H:%M}')

 

Output >>>
Product bought for $1299.50 on October 12, 2023 at 15:30

 

 

F-strings help base conversion for numeric information varieties, permitting you to transform numbers from one base to a different. So that you don’t have to jot down separate base conversion features or lambdas to view the quantity in a distinct base.

To print out the binary and hexadecimal equivalents of the decimal quantity 42 you need to use f-string as proven:

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, that is useful when it is advisable print out numbers in several bases, like binary or hexadecimal. Let’s take one other instance for decimal to octal conversion:

num = 25
print(f'Decimal {num}, in octal: {num:o}')

 

Output >>> Decimal 25, in octal: 31

 

Keep in mind Oct 31 = Dec 25? Sure, this instance is impressed by “Why do builders confuse Halloween with Christmas?” memes.

 

 

You need to use the !a and !r conversion flags inside f-strings to format strings as ASCII and repr strings, respectively.

Typically chances are you’ll have to convert a string to its ASCII notation . Right here is how you are able to do it utilizing the !a flag:

emoji = "🙂" 
print(f'ASCII illustration of Emoji: {emoji!a}')

 

Output >>>
ASCII illustration of Emoji: 'U0001f642'

 

To entry the repr of any object you need to 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

level = Point3D(0.5, 2.5, 1.5)
print(f'Repr of 3D Level: {level!r}')

 

Python dataclasses include the default implementation of __repr__ so we do not have to explicitly write one.

Output >>>
Repr of 3D Level: Point3D(x=0.5, y=2.5, z=1.5)

 

 

When working with massive language fashions like Llama and GPT-4, f-strings are useful for creating immediate templates. 

As an alternative of hardcoding immediate strings, you may create reusable and composable immediate templates utilizing f-strings. You possibly can then insert variables, questions, or context as wanted. 

In the event you’re utilizing a framework like LangChain you need to use the PromptTemplate options of the framework. However even when not, you may all the time use f-string-based immediate templates.

Prompts will be so simple as:

prompt_1 = "Give me the highest 5 greatest promoting books of Stephen King."

 

Or a barely extra versatile (however tremendous easy nonetheless):

num = 5
writer="Stephen King"
prompt_2 = f"Give me the highest {num} greatest promoting books of {writer}."

 

In some circumstances it is useful to supply context and some examples in your immediate.

Think about this instance:

# context
user_context = "I am planning to journey to Paris; I want some info."

# 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.",
	},
]

# query
user_question = "Are you able to suggest some good eating places in Paris?"

 

Right here’s a reusable immediate template utilizing f-strings. Which you need to use for any context, instance, question use case:

# Setting up the Immediate utilizing a multiline string
immediate = f'''
Context: {user_context}

Examples:
'''
for instance in few_shot_examples:
	immediate += f'''
Query:  {instance['query']}nAnswer: {instance['answer']}n'''
immediate += f'''

Question: {user_question}
'''

print(immediate)

 

Right here’s our immediate for this instance:

Output >>>
Context: I am planning to journey to Paris; I want some info.

Examples:

Query:  What are some well-liked vacationer sights in Paris?
Reply: The Eiffel Tower, Louvre Museum, and Notre-Dame Cathedral are some well-liked sights.

Query:  What is the climate like in Paris in November?
Reply: In November, Paris experiences cool and damp climate with temperatures round 10-15°C.


Question: Are you able to suggest some good eating places in Paris?

 

 

And that is a wrap. I hope you discovered just a few Python f-string options so as to add to your programmer’s toolbox. In the event you’re thinking about studying Python, try our compilation of  5 Free Books to Help You Master Python. Joyful studying!
 
 

Bala Priya C is a developer and technical author from India. She likes working on the intersection of math, programming, information science, and content material creation. Her areas of curiosity and experience embody DevOps, information science, and pure language processing. She enjoys studying, writing, coding, and low! At the moment, she’s engaged on studying and sharing her information with the developer neighborhood by authoring tutorials, how-to guides, opinion items, and extra.



Leave a Reply

Your email address will not be published. Required fields are marked *