Output formatting


Output formatting

This can be executed by using the str.format() method.
We can use the print() function to get the data as the output on the device. There are various ways to display the output on the screen, and you can either print it in a human-readable format or write to a file and save it for future usage.

. Here are some common ways to format output in Python:

  • Use the formatted string literals, like beginning a string with F or f, before opening the quotation mark.
  • The str.format() method is used for getting a fancy output format.
  • You can easily handle the string by using string slicing and concatenation and then creating any layout as required. The string type contains some methods to perform some useful operations for padding the string to given column width.

Output formatting using string modulo operator (%)

The modulo operator can format the string. It mainly interprets the left argument like the print() style format and then apply it to the right argument.

Output formatting using the format method

The format() method got added up in Python 2.6 version. Users can use {} for formatting the string as it requires more human efforts. The {} mark is used where it is required to substitute a variable and can offer detailed formatting further.

Output formatting by string method

In this method, the formatting is done using string slicing and concatenation operations.

Here, the curly braces {} are actually working as placeholders.

We can even use keyword arguments to format any type of string.

NOTE- We can also format strings like printf() style which had been previously used in C programming language. We can always use the % operator to accomplish this.

Example:

print("knowledge2life : %2d, Portal : %5.2f" % (1, 05.333)) # print integer value print("Total users : %3d, Boys : %2d" % (240, 120)) # print octal value print("%7.3o" % (25)) # print exponential value print("%10.3E" % (356.08977))

OUTPUT:

knowledge2life : 1, Portal : 5.33
Total users : 240, Boys : 120
031
3.561E+02