Python

Python String Formatting Tutorial

This python function is used to format the string by adding or replacing the placeholder’s variable value with the string defined in the format function as a parameter. It is a built-in function that supports returning the value as a print. This article will cover many elementary examples to help you in improving your existing knowledge.

Syntax of Python String Formatting

Sample. format (p0, p1…,  k0=V0, k1=V1,)

In this syntax, p0 and p1 are positional arguments, whereas k1 is the key argument having values v0 and v1, respectively. The sample contains sets of all the codes of string formatting.

These two parameters are defined below:

Positional Argument: The index written inside the curly bracket {index} can easily access it.

Key argument: The key parameters inside the curly bracket are the easily accessed list of parameters of key = value type.

Placeholder: The placeholder in a string is represented by the curly brackets {}. These may be present at any position in the string. For example, these may be empty, filled with variables, or have index numbers in them.

Empty Placeholder With a String Value

This is a simple illustration to understand the concept of formatting the string. In this example, the placeholder is passed with a string of numbers. The placeholder is empty at the start, but the format function passes the value as a parameter. This is a single-line code that can format a particular string.

String.format(3.8)

To see the output, we will use a Linux environment. Open the Ubuntu terminal, write the following command, and execute it:

$ python3 ‘/home/aqsa/Documents/resulttemp.py’

Python3 is a keyword used to fetch the data. Whereas following that keyword, we have used the path of a file. We can also use only the file name if it is located inside the python folder.

Now, execute the command. You will see that the number 3.8 is currently present on the place where curly brackets were present, showing the empty placeholder.

Placeholder Having a Variable/Keyword Inside It

In this example, we have to make use of the variables inside the curly brackets. The values of these NULL variables are defined inside the format so that when the program will be executed, the values will be automatically assigned to the variables. In the example appended below, there are two variables used, {name} and {age}. The values are initiated and defined inside the format:

.format(name= “Sanam” , age =9)

The name is Sanam, and her age is 9. These values will be assigned when we execute the following program:

From the output, you can see that the variables inside the placeholder are replaced with the values.

Formatting the String Using Center, Left, and Right alignment

Example 1: With Right Alignment

We have taken an example where the placeholder is assigned with a number and an operator {:> 20}. This indicates the formatting of the result. The space of 20 is added to the resultant word. The value that is replaced is right-aligned in the output.

Print(“I got {:>20} marks in exams”.format(80))

Now, execute the following code in a Ubuntu terminal:

In the output appended below, you can observe the value that is replaced in the placeholder and the whole string after it are now right-aligned with 20 points. It means “>” is used to add space at the left side of the string

Example 2: With Center Alignment

In this example, the exact string is used only for the variable’s value, and the operator is changed. Like the above example, here we have used “^” which is for center alignment. By using this, we can add space at both sides of the output that contains the placeholder value. In comparison, another text remains the same.

{ : ^20}

This placeholder value will add the space of 20 points on the left and right sides of the placeholder.

As shown in the output, 20 spaces are added.

Example 3: With Left Alignment

The left alignment will use the “<” operator to add space on the right side of the output, whereas the whole string is written on the right side. Thus, the placeholder will be written as {:<}.

Formating of Numbers

There are many keywords and format specifiers used in formatting a string. Some of them are given below:

  • d: Convert to a decimal integer.
  • o: Convert to octal format.
  • f: Shows the fixed-point numbers.
  • %: It multiplies the value by 100. And adds the “%” sign at the end.
  • e: Shows the exponential value.
  • X: Conversion of string in a hexadecimal format.

Now, in this article, we have used some of them to elaborate the process:

  1. It shows the conversion of the binary to the decimal value by using{:d}, which shows that the number is converted into a decimal value of 11.
  2. It converts the value in the scientific value when used in the placeholder. The {:e} is used for exponential. 70 is converted into 7.000000e+01.
  3. Conversion of a string into hexadecimal {:x} is used, and the output of 1780 is “6f4”.
  4. This example is converted in octal format by using {:o}. For example, 340 is converted into 524.

While executing the code, we will get the output as cited below:

Formatting String in the Dictionary

Here is an example of formating a dictionary. For example, let’s suppose having a dictionary named “data” contains the following information regarding a student.

Format_string = x + “:{“ + X+”}

This code is used to format a string and print the formatted data. Also, the inverted commas are removed, and a string is printed before the whole data of the dictionary.

The output will be obtained by using a similar command in the terminal.

Formatting a Class

Consider a class named “sample” having two attributes of name and age. In addition, the placeholder contains the variable name of age and name. These placeholders are also accessed with the object created for the class.

.format(p=sample)

Here, the object is initiated to access the items in a class.

The output is shown below:

Conclusion

String formatting can be done in many ways, either with or without a placeholder. With the help of operators, we have discussed the alignment factor. Formatting the class and dictionary also helped in explaining the formatting concept.

About the author

Aqsa Yasin

I am a self-motivated information technology professional with a passion for writing. I am a technical writer and love to write for all Linux flavors and Windows.