Introduction

In this post, we will explore string objects and the formatting syntax. The topics will be made clearer by ample use of practical examples. Useful links will be shared.

The progression of topics will be as per the below sequence :

  • We start with string and check all the methods and attributes.
  • We then check the str.format() method.
  • str.format() takes in arguments and keyword arguments.
  • Format strings contain “replacement fields” surrounded by curly braces {}. Anything that is not contained in braces is considered literal text, which is copied unchanged to the output.
  • “Format specifications” are used within replacement fields contained within a format string to define how individual values are presented.

Usecase

This post can be referred for string formatting in python.

Python String methods

In [37]:
print(list(dir('abcdef')))
['__add__', '__class__', '__contains__', '__delattr__', '__dir__', '__doc__', '__eq__', '__format__', '__ge__', '__getattribute__', '__getitem__', '__getnewargs__', '__gt__', '__hash__', '__init__', '__init_subclass__', '__iter__', '__le__', '__len__', '__lt__', '__mod__', '__mul__', '__ne__', '__new__', '__reduce__', '__reduce_ex__', '__repr__', '__rmod__', '__rmul__', '__setattr__', '__sizeof__', '__str__', '__subclasshook__', 'capitalize', 'casefold', 'center', 'count', 'encode', 'endswith', 'expandtabs', 'find', 'format', 'format_map', 'index', 'isalnum', 'isalpha', 'isascii', 'isdecimal', 'isdigit', 'isidentifier', 'islower', 'isnumeric', 'isprintable', 'isspace', 'istitle', 'isupper', 'join', 'ljust', 'lower', 'lstrip', 'maketrans', 'partition', 'replace', 'rfind', 'rindex', 'rjust', 'rpartition', 'rsplit', 'rstrip', 'split', 'splitlines', 'startswith', 'strip', 'swapcase', 'title', 'translate', 'upper', 'zfill']

Decoding string content

Check out the grammar for the contents of the string.

Replacement field

Check out the grammar for a replacement field.

Format Specification for mini language

The general form of a standard format specifier is:

format_spec ::= [[fill]align][sign][#][0][width][grouping_option][.precision][type] fill ::= align ::= "" | "=" | "^" sign ::= "+" | "-" | " " width ::= digit+ grouping_option ::= "_" | "," precision ::= digit+ type ::= "b" | "c" | "d" | "e" | "E" | "f" | "F" | "g" | "G" | "n" | "o" | "s" | "x" | "X" | "%"

Examples

In [15]:
'{: 6.2f}'.format(3.141592653589793)
Out[15]:
'  3.14'
In [16]:
'{:06.2f}'.format(3.141592653589793)
Out[16]:
'003.14'
In [17]:
'{:06.2f}%'.format(3.141592653589793)
Out[17]:
'003.14%'
In [30]:
# https://python-reference.readthedocs.io/en/latest/docs/str/formatting.html
# https://www.w3resource.com/python-exercises/string/python-data-type-string-exercise-37.php

print('|{:<6.0f}|'.format(314.0))
print('|{: 6.0f}|'.format(314.0))
print('|{:^6.0f}|'.format(314.0))
|314   |
|   314|
| 314  |
In [19]:
print('|{:<6.1f}|'.format(314.23))
print('|{: 6.1f}|'.format(314.23))
print('|{:^6.1f}|'.format(314.23))
|314.2 |
| 314.2|
|314.2 |
In [36]:
print('|{:<6.1f}|'.format(314.23))
print('|{:>06.1f}|'.format(314.23))
print('|{:06.1f}|'.format(314.23))
print('|{:^6.1f}|'.format(314.23))
|314.2 |
|0314.2|
|0314.2|
|314.2 |

Using variable as Padding width input

In [20]:
width = 20
py, vg = "Python", "Very Good"
print(f"{py:>{width}s} : {vg:>{width}s}")
              Python :            Very Good
In [21]:
# https://stackoverflow.com/questions/3228865/how-do-i-format-a-number-with-a-variable-number-of-digits-in-python
'{num:0{width}}'.format(num=123, width=6)
Out[21]:
'000123'
In [22]:
# https://stackoverflow.com/questions/3228865/how-do-i-format-a-number-with-a-variable-number-of-digits-in-python
# Use of f literals
num=123
fill='0'
width=6
f'{num:{fill}{width}}'
Out[22]:
'000123'

Example of left and right alignment

In [23]:
health_data = {'George': {'McDonalds': {'Food': 'burger', 'Healthy':False},
                          'KFC':       {'Food': 'chicken', 'Healthy':False}},
               'John':   {'Wendys':    {'Food': 'burger', 'Healthy':False},
                          'McDonalds': {'Food': 'salad', 'Healthy': True}}}
In [24]:
for i in health_data.keys():
    for j in health_data[i].keys():
        for k in health_data[i][j].keys():
            print("{:<10} : {:>10} - {:>10} - {:>10}".format(i, j,k, health_data[i][j][k]))
George     :  McDonalds -       Food -     burger
George     :  McDonalds -    Healthy -          0
George     :        KFC -       Food -    chicken
George     :        KFC -    Healthy -          0
John       :     Wendys -       Food -     burger
John       :     Wendys -    Healthy -          0
John       :  McDonalds -       Food -      salad
John       :  McDonalds -    Healthy -          1
In [26]:
class bold_color:
   PURPLE = '\033[95m'
   CYAN = '\033[96m'
   DARKCYAN = '\033[36m'
   BLUE = '\033[94m'
   GREEN = '\033[92m'
   YELLOW = '\033[93m'
   RED = '\033[91m'
   BOLD = '\033[1m'
   UNDERLINE = '\033[4m'
   END = '\033[0m'

print("The output is:" + bold_color.BOLD + 'Python Programming !' + bold_color.END+"Check")
print("The output is:" + bold_color.PURPLE + 'Python Programming !' + bold_color.END+"Check")
print("The output is:" + bold_color.RED + 'Python Programming !' + bold_color.END+"Check")
print("The output is:" + bold_color.CYAN + 'Python Programming !' + bold_color.END+"Check")
print("The output is:" + bold_color.GREEN + 'Python Programming !' + bold_color.END+"Check")
print("The output is:" + bold_color.GREEN + bold_color.UNDERLINE + 'Python Programming !' + bold_color.END+"Check")
The output is:Python Programming !Check
The output is:Python Programming !Check
The output is:Python Programming !Check
The output is:Python Programming !Check
The output is:Python Programming !Check
The output is:Python Programming !Check