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 :
Usecase
This post can be referred for string formatting in python.
print(list(dir('abcdef')))
Format Specification for mini language
https://docs.python.org/3/library/string.html#formatspec
Check out the grammar for the contents of the string.
Check out the grammar for a replacement field.
The general form of a standard format specifier is:
'{: 6.2f}'.format(3.141592653589793)
'{:06.2f}'.format(3.141592653589793)
'{:06.2f}%'.format(3.141592653589793)
# 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))
print('|{:<6.1f}|'.format(314.23))
print('|{: 6.1f}|'.format(314.23))
print('|{:^6.1f}|'.format(314.23))
print('|{:<6.1f}|'.format(314.23))
print('|{:>06.1f}|'.format(314.23))
print('|{:06.1f}|'.format(314.23))
print('|{:^6.1f}|'.format(314.23))
width = 20
py, vg = "Python", "Very Good"
print(f"{py:>{width}s} : {vg:>{width}s}")
# 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)
# 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}}'
health_data = {'George': {'McDonalds': {'Food': 'burger', 'Healthy':False},
'KFC': {'Food': 'chicken', 'Healthy':False}},
'John': {'Wendys': {'Food': 'burger', 'Healthy':False},
'McDonalds': {'Food': 'salad', 'Healthy': True}}}
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]))
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")