String
in Python can be formatted with format method( ) that is a multifunctional tool and robust to format String
# Default Order
Stringl = "{} {} {}".format('MySkill', 'For', 'Learning')
print("\\nPrint String in Positional order: ")
print(Stringl)
# Positional Formatting
Stringl = "{1} {0} {2}".format('MySkill', 'For', 'Learning')
print("\\nPrint String in Positional order: ")
#Keyword Formatting
Stringl = "{l} {f} {g}".format(g='MySkill', f='For', l='Learning')
print("\\nPrint String in order of Keywords: ")
print(Stringl)
Print String in Positional order:
MySkill For Learning
Print String in Positional order:
Print String in order of Keywords:
Learning For MySkill
Format method in String
is fulfilled with parenthesis {} as placeholder that can accommodate suitable arguments with position or keywords to determine the order.
# String formatting with % Operator
import itertools-
name = ['Tom', 'Sam', 'Ron']-
age = [30, 40, 25]-
for i, j in zip(name, age):-
print('The manager is %s and his age is %d % (i, j)-'
The integer number such as Binary, Hexadecimal, etc and float can be rounded up or be shown in form of exponent with the determined format.
# Formattting of Integers
Stringl = "{0:b}".format(16)
print("\\nBinary representation of 16 is")
print(Stringl)
# Formatting of Floats
Stringl = "{0:e}".format(165.6458)
print("\\nExponent representation of 165.6458 is ")
print(Stringl)
# Rounding off Integers
Stringl = "{0:2f}".format(1/6)
print("\\none-sixth is : ")
print(Stringl)
Binary representation of 16 is
10000
Exponent representation of 165.6458 is
1.656458e+02
one-sixth is :
0.166667
A String
also can let it be as () or in the middle (^). It is justified with the use of format determination, divided by semicolon (:)
# String alignment
Stringl = "|{:<10}|{:^10}|{:>10}|".format('MySkill','for','Learning')
print("\\nLeft, center and right alignment with Formatting: ")
print(Stringl)
# To demonstrate aligning of spaces
Stringl = "\\n{0:^16} was founded in {1:<4}|".format("MySkillForLearning",
2021)
print(Stringl)
Left, center and right alignment with Formatting:
|MySkill | for | Learning|
MySkillForLearning was founded in 2021|