- Nov 6, 2024
f-strings in Python
- DevTechie Inc
Before Python 3.6, there were two basic tools for interpolating (mixing) values, variables, and expressions within string literals — (1) The string interpolation operator (%) (the math’s modulo operator) and (2) The string.format() method. This article talks about the new feature — “f-strings” “f-strings” were introduced in Python 3.6.
f-strings
If you as a developer struggle with string formatting in Python, then do not worry! There are many like you including me. In fact, for most of the developers creating formatted strings is a daunting task. String Formatting is the process of creating dynamic messages which have a mix of strings and values.
To address the issue of string formatting tasks, Python 3.6 introduced a new string formatting style known as “f-strings.” Also known as formatted string literals, f-strings are string literals with f or F before the opening quotation mark.
f-strings can include Python expressions which have replacement fields with curly braces. Python will replace the replacement fields with their corresponding values. This behavior transforms f-strings into a complete string interpolation tool.
This new string formatting method allows you to insert Python expressions inside string literals (constants).
f-strings has better readability and most often faster than .format() method.
Here’s a short example to give you a sense of the feature.
Code:
stu_name = "Akhanda"
stu_age = 35
stu_fee = 2562str =f"Name: {stu_name} , Age: {stu_age}, Fee: {stu_fee} "
print (str)Output:
Name: Akhanda , Age: 35, Fee: 2562As you can see, this prefixes the string constant with “f” — hence the name “f-strings.” This new formatting syntax is effective because you can insert arbitrary Python expressions in f-strings.
You can even perform inline arithmetic using it. The below code demonstrates this.
Code:
stu_name = "Akhanda"
stu_age = 35
stu_tution_fee = 2562
stu_hostel_fee = 52.45str =f"Name: {stu_name} , \n Age: {stu_age}, \n Total Fee: {stu_tution_fee + stu_hostel_fee} "
print (str)Output:
Name: Akhanda ,
Age: 35,
Total Fee: 2614.45String interpolation becomes much readable and compact when it is done with the f-string syntax. Operators or methods are no longer required in
f-string. You just insert the desired objects/values or expressions in your string literal using curly brackets.
It’s worth noting that Python analyzes f-strings at runtime. So, when Python executes the line of code that contains the f-string, all variables stu-name, stu_age, stu_tution_fee, stu_hostel_fee are interpolated into the string literal. Python can only interpolate these variables since you defined them before the f-string; this means that variable/objects must be in scope when Python evaluates the f-string.
F-strings make the string interpolation process simple, rapid, and straightforward. The syntax is similar to the one you use with
format(), but less verbose. You simply need to begin your string literal with a lowercase or uppercase f, and then wrap your values, objects, or expressions in curly brackets at particular locations.
Formatted string literals are a Python parser feature that translates f-strings to a list of string constants and expressions. They are then merged together to create the final string.
The above example for doing arithmetic in f-strings is very simple. However, f-strings are more capable. Let’s considermore complex expressions which have function (method) calls and comprehensions.
Method/Function call in f-string
The below code demonstrates a method call in f-strings.
Code:
company_name = "devtechie"
print (F"This article is brought to you by { company_name.capitalize() }" )Output:
This article is brought to you by DevtechieUsing comprehensions in f-strings
Suppose you want to print a table using comprehensions, the below code does this using f-strings. The below code embeds a list comprehension in the f-strings.
Code:
print ( f"{[2*n for n in range(1,11)]}" )Output:
[2, 4, 6, 8, 10, 12, 14, 16, 18, 20]Format specifiers in f-strings!
The format() method also supports format specifiers. Format specifiers are the strings which are inserted into replacement fields and used to format values.
Like the format() method, f-strings support the string formatting mini-language. So, you can utilize format specifiers in your f-strings as well.
The expressions embedded in an f-string are evaluated at runtime. The result is then formatted by Python’s internally with the aid of __format__() — a special method. This method understands the string formatting protocol. The same formatting protocol is used by the string.format()method of and the built-in format() function to create formatted strings.
Code:
stu_name = "Akhanda"
stu_age = 35
stu_tution_fee = 2562
stu_hostel_fee = 52.45
str = f"Name: {stu_name} , \n Age: {stu_age}, \n Total Fee: {stu_tution_fee + stu_hostel_fee:.3f} "
print (str)Output:
Name: Akhanda ,
Age: 35,
Total Fee: 2614.450Text alignment in f-strings
Above example formats a float value using “.3f” format specifier. Format specifiers in f-strings can also align text.
Center Alignment
The below example of format specifiers does a center alignment of text.
Code:
print (f"{'Centered string':=^30}")Output:
=======Centered string========The above format specifier :=^30 makes the string of 30 width. Hence to do so, it pads the string with the character “=”. Further the ^ symbol centers the input using the padding within the total string length.
Left Alignment
Just replace the symbol ^ by < for left aligning the text.
Code:
print (f"{'Centered string':=<30}")Output:
Centered string===============Right Alignment
The > symbol is used for right aligning the text.
Code:
print (f"{'Centered string':@>30}")Output:
@@@@@@@@@@@@@@@Centered stringThe <, ^, and > symbols inside the placeholders (format specifiers) indicate left, center, and right alignments, respectively. The number that follows these symbols indicates the string’s total width.
Other Format Specifiers in f-strings
You have already seen a format specifier which formats a float value using “.3f” format specifier. Let’s look at another formatting specifier for numeric values in f-strings.
Code:
cost = 6525678
print (f"The cost of the item is : ${cost:{'_'}.2f}")Output:
The cost of this item is : $6_525_678.00Formatting dates
Dates can also be formatted using a format specifier as shown in the below code snippet.
Code:
date = [7, 2, 2024] # or you can use a tuple instead of a list i.e. date = (7, 2, 2024),print (f"Date: {date[0]}-{date[1]}-{date[2]}")print (f"Date: {date[0]:02}/{date[1]:02}/{date[2]}")Output:
Date: 7-2-2024
Date: 07/02/2024Recapitulate
Python f-strings offer a simple way to interpolate and format strings. They are clear, simple, and less error-prone than typical string interpolation and formatting tools like the format() method and the modulo operator (%). An f-string is actually slightly faster than those tools!