Pad or Fill a String by a Variable in Python Using F-String

F-string stands for formatted string. It was introduced by Python Version 3.6 and was quickly put to use for simple string formatting. An F-string is a literal string whose syntax begins with f and ends with {}. The placeholder used to store variables will be updated based on the names and values of those variables.

String formats like str. format(), string.Template() and %-formatting are already available. However, the primary drawback of utilising them was that the implementation was difficult to carry out. For this reason, Python introduced the f-string because of its simple and straightforward syntax.

Take into account, for instance, all three of the following:

1. Using %-formatting

Program Explanation:

This Python code gives the string "nightfury1" as the name of the variable. The % operator, also known as the string formatting operator, is then used to insert the value of the name into the specified string template. The string template used is JavaTPoint, a contributor. During the formatting process, the value contained in the variable name takes the place of the string placeholder, %s, in this instance. The final string is written to the console following formatting. The conclusion would be "nightfury1 is a contributor to JavaTPoint" if the name in this instance were "nightfury1." Variables and strings can be concatenated in an organized manner using this method.

Output:

nightfury1 is JavaTPoint, a contributor

2. Using str. format()

Program Explanation:

This Python code gives the string "nightfury1" as the name of the variable. The format method is then used to insert the name value into the specified string template. During the formatting process, the value that is stored in the variable name is used in place of the curly braces, which are used as placeholders in the template. The final string is written to the console following formatting. The conclusion would be "nightfury1 is a contributor to JavaTPoint" if the name in this instance were "nightfury1." Text and variables are concatenated in a formatted manner using this strategy, which makes use of the format method.

Output:

nightfury1 is JavaTPoint a contributor.

3. Using f-string

Program Explanation:

Using an f-string, or formatted string literal, this Python code creates a string with a dynamic value. An f-string is used to create a prepared text following the addition of the string "nightfury1" to the name of the variable. The variable name is immediately inserted into the f-string placeholders created by the curly braces during string interpolation. The message "nightfury1 is a contributor to JavaTPoint" would be displayed by the code. F-strings are a straightforward and accessible technique for directly inserting expressions, variables, or even computations into string literals.

Output:

nightfury1 is JavaTPoint a contributor.

Approaches using f-string:

1. f-string expressions: It returns the result after evaluating the string enclosed in {}.

Program Explanation:

Using an f-string, or formatted string literal, this Python code makes a string with dynamic values. "nightfury1" and "Technical Content Writer Intern" are the values. They are saved in the post and name variables. Curly-braced placeholders for these variables are included in the f-string. During string interpolation, the variables' values are directly entered into these placeholders. The output of the code would be "nightfury1 is a JavaTPoint Technical Content Writer Intern." Using f-strings is a concise and expressive method for creating strings with embedded variables or expressions.

Output:

nightfury1 is JavaTPoint Technical Content Writer Intern.

2. f-string dictionaries: A dictionary has key-value properties, so an f-string formats strings using dictionary properties.

Program Explanation:

In this Python code, a dictionary called JtP defines two key-value pairs: "name" with the value "nightfury1" and "post" with the value "Technical Content Writer Intern." The values for the dictionary keys "name" and "post" are put into the formatted string created by the f-string by using curly brackets as placeholders. JavaTPoint Technical Content Writer Intern nightfury1 is the output of the code. Using f-strings to retrieve and display values from a dictionary within a formatted string is demonstrated in this code.

Output:

nightfury1 is JavaTPoint Technical Content Writer Intern.

3. f-string debug: Debugging the value included in the provided expression assesses the result.

Program Explanation:

Using f-strings and the math. cos() and math.sin() methods, respectively, this Python code prints the cosine and sine values of the variable x after importing the math module and assigning the value 0.5 to it. The output of the code will display the calculated cosine and sine values for the given value of x. This code demonstrates how to use the math module to calculate trigonometric functions and return the results as an f-string-formatted string.

Output:

math.cos(0.5) = 0.8775825618903728
math.sin(0.5) = 0.479425538604203

4. f-string multiline: The f character appears before each string, which is evaluated when enclosed in round brackets. The result is returned on many lines.

Program Explanation:

In this Python code, the values of the variables name, org, and post correspond to an individual's name, organization, and job position, respectively. The code then uses an f-string to format the individual's information, which includes their name, organization, and job position. The print() instruction is used to display the content of the prepared string at the end. This example shows how to make use of f-strings to create dynamic, well-formatted strings that make it easy to build and present information in a way that is easy to understand.

Output:

Name : nightfury1
Organization: JavatPoint
Post: Technical Content Writer Intern.

Using the f-string for padding and filling:

F-string padding is the ability to enter and specify a format with digits after a decimal or a specific integer or DateTime.

1. 0-padding: Here, we apply 0-padding by adding {variable: 0N} inside the f-string {} syntax, where N refers to the total no. of digits.

Program Explanation:

Using a for loop, this Python code traverses the entire range of numbers from 1 to 5 (inclusive). The current value of i is output inside the loop using an f-string. The specifier of the format: The inclusion of 02 in "i:02" ensures that the printed number contains at least two digits. A single-digit number will have a leading zero added to it to make it easier to understand. Because it keeps the width of the output constant, this is helpful when working with numbers that may have different lengths. The code prints the numbers from 01 to 05 with leading zeros when a number is less than 10.

Output:

The number is 01
The number is 02
The number is 03
The number is 04
The number is 05

2. date-padding: Here, we also format the dates by using the DateTime module and adding up the desired format in {} like {date: directive}.

Program Explanation:

This Python code uses the datetime module to get the current date and time. The now() function of the datetime class is called to obtain this information. The acquired datetime object is then output as an f-string.

The f-string includes the following format specifier: % Y-%m-%d. The hour (00 to 23) is represented by %H in the formula %H:%M, the month (%m) is the month as a zero-padded decimal number, the day of the month (%d) is the day of the month as a zero-padded decimal number, and the minute (%) is represented by %M. By utilizing this format specifier, the output can be formatted to display the current time in the format that is desired, such as "YYYY- MM."

Output:

Current Time:  2024-01-26 17:34

3. space-padding: In this case, we add spaces to a string of length N, denoted as {variable: N}. It will thus insert additional spaces before the supplied variable if N is 4 and the given variable is "a."

Program Explanation:

This Python code iterates over the integers 1 through 5 (inclusive) using a for loop. Each number is printed inside the loop using an f-string, which has a width of four characters. The format specifier "4" in the f-string indicates that the value of "i" should be positioned to the right within a field with a width of 4.

Output:

The number is    1
The number is    2
The number is    3
The number is    4
The number is    5

4. justify-padding: As is common knowledge, strings are justified to the left by default. However, by using {variable: >N}, where N is the entire length, we may correctly explain them with the aid of f-strings.

Program Explanation:

This Python program prints four strings (s1, s2, s3, s4) with correct alignment inside a 13-character field width by using formatted string literals, or f-strings. To achieve the desired alignment, each string is printed with extra spaces on its left side thanks to the f'{string: >13}' syntax. The result shows that the strings are arranged to the right within the specified field width, resulting in 13 characters for each line.

Output:

Javatpoint
     vatpoint
       tpoint
        point

F-string filling is the process of entering and defining the format using numbers or symbols before and after the supplied string.

1. hardcoded - filling: In this case, the filler or symbol is added using the f-string syntax's hardcode.

Program Explanation:

This Python program prints the word "java" with various fill characters and alignments inside a 15-character field width by using formatted string literals, or f-strings.

  • The asterisk (*) character is used to illustrate left filling in the line print(f'{"java":*>15}'). Asterisks are positioned on the left side of the word "java" until the character count exceeds fifteen.
  • The correct filling with asterisks is demonstrated by the line print(f'"java":*15'). The word "java" is positioned to the left and padded with asterisks on the right side to make the entire width of 15 characters.

The result will illustrate the effects of left and right filling with asterisks by displaying both forms of the word "java" inside the chosen field width and alignment.

Output:

***********java
java***********

2. variable - filling: In this case, the print() function was used with an f-string filled curly braces expression.

Program Explanation:

A loop iterates across a range in this Python program, starting at 6 and going up to the designated width (15 in this example). An f-string is used to output a formatted string throughout each iteration. The alignment of the string "java" is to the left, and the right side is padded with the designated filler character (an asterisk, '*'). With every iteration, the field's width grows, showing how the string is gradually expanding in addition to the filler characters' varying widths.

Output:

java**
java***
java****
java*****
java******
java*******
java********
java*********
java**********

Benefits of f-strings:

  • It's the quickest way to format strings in Python.
  • It reads easier.
  • It is brief in style.
  • Because of its reduced error proneness, there are fewer opportunities for mistakes while formatting strings.
  • It is less verbose or has less formatting syntax.