Python: String Formatting – 1

Python has various methods for string formating to control over the appearance of the displayed data on the screen. This tutorial has explained these methods with examples.

String Modulo Operator

In the programming language, the modulo operator has generally used with numbers to computing the remainder from the division. But, Python’s string modulo works a very different way. It is used to format the string with values of the expression.

Syntax:

<format_string> % <values>
Where,
format_string: A string containing conversion specifiers
values: values inserted into <formated_string> in place of the conversion specifiers

Examples:

In [1]:
name = "mark"
output = "Hello, %s." % name
print(output)
Out[1]:
Hello, mark.

Here,  %s in the format_string denotes the conversion specifier. In the output formated string the values are replaced with conversion specifiers defined in the format_string in order.

If there are multiple values to insert in the string, then use the tuple as demonstrate in the below example.

In [2]:
output = "The total cost of the %d %s is $%.2f." %(5,"computers",20000)
print(output)
Out[2]:
The total cost of the 5 computers is $20000.00.

.     .     .

Conversion Specifiers

Conversion specifier has shown in the formate_string begin with the % character. It determines how the values are displayed. Conversion specifiers consist of three components:

%[<flags>][<width>][.<precision>]<type>

Here, % and <type> is a mandatory field, whereas the flags, width and precision are optional fields.

  • flags           : used to apply finer control over string formatting.
  • width         : Specifies the minimum width of the formatted result.
  • .precision : Specifies the precision of the floating-point number.
  • type            : Specifies the conversion type to be performed.

 

Conversion Type

  • %d, %i, %u  – Represent the integer value
  • %s, %r, %a   – Represent the string value
  • %f, %F          – Represent the float value
  • %e, %E         – Represent the Exponential value
  • %x, %X         – Represent the Hexadecimal Integer
  • %c                   – Represent the single character
  • %o                   – Represent the octal Integer

 

Examples:

# d,i and u indicates the Integer values.
In [3]: print("%d + %i = %u" % (5,3,8))
Out[3]: 5 + 3 = 8
# f and F indiactes the float value
In [4]: print("%f + %.3f = %.4F" % (5,3,8))
Out[4]: 5.000000 + 3.000 = 8.0000

 

The Width Specifier

Width specifies the length of the output field. If the specified length value is larger than the output, the extra space is padded to output. By default the output is right-justified. If the specified length value is shorter than the output, then there is no effect of the width specifier.

In [5]: print("%10s -> $%d" %("Apple",24))
Out[5]: '     Apple -> $24'
In [6]: print("%3s -> $%d" %("Apple",24))
Out[6]: Apple -> $24

 

The .precision specifier

The precision specifies the number of digit after the decimal point of the floating-point number. It affects the floating-point, string and exponential types.

In [7]: print("%.1f + %.2f = %.4F" % (5.333,3.639,8.972))
Out[7]: 5.3 + 3.64 = 8.9720

The precision value in string type specifies the length of the string and the output string is truncated to the specified length.

In [8]: print("%.5s" % "Information")
Out[8]: Infor

 

Width & Precision together

In [9]: print("%15.5s" % "Information")   # width: 15 & precision: 5
Out[9]: '               Inform'
In [10]: print("%10.3F" % 5.123456)
Out[10]: '        5.123'

 

The flag specifier

1.  Flag: 0

When the specified value of the width field is larger than the output length, the extra space is padded to the output. This 0-Flag padded the string with zero instead of space.

In [11]: print("%010d" % 22222) # 0- Flag & width: 10
Out[11]: 0000022222

2. Flag: –

When the specified value of the width field is larger than the output length, the extra space is padded to the output and the output value is right-justified by default. But, Flag- will be used to print the output left-justified.

In [12]: print("%-10d" % 22222) # Flag: - & width: 10 
Out[12]: '22222     '

3. Flag: +

The Flag + add the plus sign to the left of the numeric value.

In [13]: print("%+d" % 222) # Flag: +
Out[13]: '+222'

4. Flag: ‘  ‘(space character)

The Flag ‘  ‘(space character) makes a single space before the numeric value.

In [14]: print("% d" % 222) # Flag: ' '
Out[14]: ' 222'

5. Flag: #

Generally, the floating-point number will not display a decimal point, if there are not any digit exist after the decimal point. The Flag # force to include the decimal point in the formatted output.

In [15]: print('%.1f' % 52)      # 1-decimal point
Out[15]: '52.0'

In [16]: print('%.0f' % 52)      # 0-decimal point
Out[16]: '52'

In [17]: print('%#.0f' % 52)
Out[17]: '52.'

For the Hexadecimal and Octal type, the Flag# force to include the base information in the formatted output. This flag adds a leading ‘0o’ for octal type and adds a leading ‘0x’ or ‘0X’ for hexadecimal value.

In [18]: print("%#o" % 14)
Out[18]: '0o16'

In [19]: print("%#x" % 10)
Out[19]: '0xa'

Note: The integer type avoids to consider Flag-#.

.     .     .

Inserting ‘%’

The modulo ‘%’ character in the format_string indicates the conversion specifier. But, if you want to insert % character in the output, Python will throw the error. Let’s see the example

In [20]: print("%s %" % "Python")
Out[20]: 
Traceback (most recent call last):
  File "test.py", line 1, in <module>
    print("%s %" % "Python")
ValueError: incomplete format

We can insert the % character in the output by using the two consecutive % characters in the format string.

In [21]: print("%s %%" % "Python")
Out[21]: Python %

.     .     .

Leave a Reply

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

Python Tutorials