Python Print Format

There are various ways to convey a program’s output. Data is printed in a human-readable format, saved to a file for later use, or sent in any other format you specify. Users frequently desire more control over output formatting than just printing space-separated values. There are various options for output formatting.

To utilize formatted string literals, precede the initial quotation mark or triple quotation mark with f or F. The str. format() method of strings allows users to make a more aesthetically pleasing output.

Python Print Format

Users can construct any layout they wish by employing string slicing and concatenation techniques to handle all string handling. The string type includes a few methods used to pad strings to specific column width. When we need to print out more than two values, we utilize the print function in two methods. The simplest, but not the most beautiful, the method is as follows:

<div class="wp-block-codemirror-blocks-code-block code-block">
<pre>num_one = 127
num_two = 21
print(num_one, num_two, num_two * num_one)</pre>
</div>

To print the results, we used to print with a comma-separated list of values, as seen in the example above. Blanks are used to separate all values, which is the default behavior. If we assign an arbitrary string to the print function’s keyword parameter “sep,” we can change the default value. We could also use the string concatenation operator to create a new string from the following values.

<div class="wp-block-codemirror-blocks-code-block code-block">
<pre>num_one = 127
num_two = 21

print(str(num_one) + " " + str(num_two) + " " + str(num_two * num_one))</pre>
</div>

In this case, the second method is inferior to the first.

The string class uses the modulo operator ” % ” to do string formatting. As a result, it’s sometimes referred to as the string modulo (or even modulus) operator, even though it has little in common with the true modulo calculation on numbers. Because it interpolates numerous class types (such as int, float, and so on) into a prepared string, it’s also known as “string interpolation.”

In many circumstances, the string produced by the string interpolation method is uniquely used to output values. However, it establishes the appropriate format for storing data in a database.

The string method format, introduced in Python 2.6, should be used instead of this old-style formatting. Sadly, string modulo ” %” is still available in Python3; worse, it is still extensively used. That’s why we go over it thoroughly in this tutorial. When you come across it in Python code, you should be able to grasp it. However, this outdated formatting method may be phased out of the language shortly. As a result, you should become familiar with the str.format().

Using the String modulo operator(%) to format the output

String formatting is also done with the % operator. It evaluates the left argument like printf() does in C language strings before applying them to the right parameter. Although Python does not have a printf() function, it does contain the functionality of the old printf. The string class overloads the modulo operator % to perform string formatting for this purpose. As a result, it’s often referred to as a string modulo (or even modulus) operator.

The string modulo operator ( % ) is still present and commonly used in Python(3.x). However, the former formatting method is no longer used in the language.

<div class="wp-block-codemirror-blocks-code-block code-block">
<pre># program for showing how to use the string modulo operator(%%) to print fancier output

# printing the integer and float value
print("Codeunderscored : %%2d, Portal : %%5.2f" %% (1, 05.333))

# printing the integer value
print("Total Employees : %%3d, Men : %%2d" %% (240, 120))

# printing the octal value
print("%%7.3o" %% (25))

# printing the exponential value
print("%%10.3E" %% (356.08977))</pre>
</div>

In our example, there are two of them: “%2d” and “% 5.2f.” A format placeholder has the following general syntax:

<div class="wp-block-codemirror-blocks-code-block code-block">
<pre>%%[flags]
[width][.precision] type</pre>
</div>

Let’s take a look at our example’s placeholders. The first placeholder, “% 2d,” refers to the first element of our tuple, which is the integer 1. Two characters are put on the number. The output is padded with one leading blank because 1 is only one digit.

The second one, “%5.2f,” is a float number format description. It begins with the % character, as do other placeholders. The entire number of digits the string should contain is then given. The decimal point and all digits before and after the decimal point are included in this number.

Our float number, 05.333, requires a five-character format. The precision, or decimal component of the number, is set to 2, the number after the “.” in our placeholder. Finally, the letter “f” stands for “float” in our placeholder.

Using the String method format to modify the output

Python introduced the format() function (2.6). The string format approach necessitates more manual work. Users can use it to indicate where a variable will be substituted and offer detailed formatting directions, but they must also supply the data to be prepared. This method uses positional formatting to concatenate components within an output. The general flow of this approach is the use of a template, as illustrated below.

<div class="wp-block-codemirror-blocks-code-block code-block">
<pre>template.format(p0, p1, ..., k0=v0, k1=v1, …)</pre>
</div>

The template (or format string) is a continuous text string that comprises one or more format codes (fields to be substituted). Curly brackets {} are used to surround the “fields to be replaced.”

The curly braces and the “code” inside are replaced with a formatted value from one of the arguments, based on the rules we will define shortly. Anything else that isn’t in curly braces will be printed exactly as it is, with no alterations. If you need to print a bracing character, you must escape it by doubling it: {{and}}.

The .format() method accepts two types of parameters. The list of arguments may begin with zero or more positional parameters (p0, p1, etc.) and continue with zero or more keyword arguments of the form name=value. The index of a positional parameter of the format method can be accessible by placing it after the opening brace. For example,{ 0} accesses the first parameter, {1} accesses the second, and so on.

A colon can follow the index inside the curly brackets and a format string, similar to the string modulo notation we studied at the start of this article, for example, {0:5d}.

The positional argument specifiers inside the braces can be omitted if the positional parameters are utilized in the order in which they are written, thus ‘{} {} {}’ corresponds to ‘{0} {1} {2}’. However, if you want to access them in various orders, you’ll need them: ‘{2} {1} {0}’.

<div class="wp-block-codemirror-blocks-code-block code-block">
<pre># program illustrating the use of format() method in Python

# using format() method
print(' {} is prime for "{}!"'.format('CodeUnderscored', 'Programming'))

# utilizing the format() function and a reference to an object's position
print('{0} and {1}'.format('Code', 'Interface'))

print('{1} and {0}'.format('Code', 'Interface'))


# f-Strings can also be used to format the above data.

However, this capability is only available in Python 3.6 and higher.

print(f" {'CodeUnderscored'} is prime for \"{'Programming'}!\"")

#utilizing the format() function and a reference to an object's position
print(f"{'Code'} and {'Interface'}")</pre>
</div>

The format() method replaces the brackets and characters within them (called format fields) with the objects passed in. A number in brackets can denote the object’s position supplied into the format() method.

<div class="wp-block-codemirror-blocks-code-block code-block">
<pre># program showing the use of format() method in Python

# combination of both keyword and  positional  arguments
print('The top Programming site  is {0}, {1}, and {other}.'
	.format('CodeUnderscored', ' followed by', other ='the rest'))

# using a number with the given method
print("CodeUnderscored :{0:2d}, Site :{1:8.2f}".
	format(12, 00.546))

# varying the positional argument
print("The subsequent argument is: {1:3d}, first one: {0:7.2f}".
	format(47.42, 11))

print("CodeUnderscored: {a:5d}, Site: {p:8.2f}".
	format(a = 453, p = 59.058))</pre>
</div>

Example: program illustrating the format() used in the dictionary

<div class="wp-block-codemirror-blocks-code-block code-block">
<pre>tab = {'CodeUnderscored': 4127, 'is prime for': 4098, 'Programming': 8637678}

# use of the method format() in the dictionary
print('CodeUnderscored: {0[code]:d}; For: {0[for]:d}; '
	'UnderScored: {0[portal]:d}'.format(tab))

data = dict(fun ="CodeUnderscored", adj ="Site")

# using the method format() in the  dictionary
print(" {coding} is fun {adj}".format(**data))</pre>
</div>

Using the String technique to format output

String slicing and concatenation procedures are used to format this output. The string type offers some methods for formatting output more elegantly. str.ljust(), str.rjust(), and str.centre() are all useful techniques for formatting output.

<div class="wp-block-codemirror-blocks-code-block code-block">
<pre># program for formatting an output using the method - string()

code_string = "CodeUnderscored is prime for Coding"

#Printing a string with the center of the page aligned  
print ("Center aligned string with fillchr: ")
print (code_string.center(40, '#'))

# Using "-" padding to print the aligned to the left string
print ("The string that is aligned to the left is: ")
print (code_string.ljust(40, '-'))

# With "-" padding, the right-aligned string is printed here.
print ("The string that is aligned to the right is: ")
print (code_string.rjust(40, '-'))</pre>
</div>

Conclusion

This article looks deeper at the numerous techniques to make prettier output in Python. We have shown you all the options, but we recommend using the string class’s format method. However, the most versatile and Pythonic approach is “string format.”

Similar Posts

Leave a Reply

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