top of page

Python  – Learn from Basic to Advanced

Python: Formatting Data with print() Statement

Formatting Data with print() Statement

  • There are many ways to present the output of a program, data can be printed in a human-readable form, or written to a file for future use. 

  • print() supports formatting of console output. You can choose how to separate printed objects, and you can specify what goes at the end of the printed line. 

  • There are several ways to format output.

    • To use formatted string literals, begin a string with f or F before the opening quotation mark or triple quotation mark.

    • The str.format()method of strings help a user to get a fancier Output

Formatting output using String modulo operator(%)

  • The modulo operator (%) is usually used with numbers, in which case it computes remainder from the division.

  • The % operator can also be used for string formatting.

In general, the string formatting operator is used like this:


<format_string> % <values>

​

On the left side of the % operator, <format_string> is a string containing one or more conversion specifiers. The <values> on the right side get inserted into <format_string> in place of the conversion specifiers. The resulting formatted string is the value of the expression.

Python’s data format characters

 Symbol         Description

​

  %c                       character

​

  %s                       string

​

  %d                       signed decimal integer

​

  %i                        integer

​

  %u                       unsigned decimal integer

​

  %o                       octal integer

​

  %f                        floating number

​

  %e                       exponential notation with lowercase e

​

  %E                       exponential notation with lowercase E

​

  %x                       hexadecimal integer in lowercase

​

  %X                       hexadecimal integer in uppercase

          

Example: Write a Python program to find the area of a triangle given that its base is 20 units and height is 40 units.

base = 20

height = 40

area = 0.5 * base * height

print("The Area is: ", area)

OUTPUT:

The Area is: 400

Formatting output using String modulo operator(%)
bottom of page