Formatting output using String modulo operator(%)
The % operator can also be used for string formatting. It interprets the left argument much like a printf()-style format string to be applied to the right argument.
Example:
1 2 3 4 5 6 7 8 9 10 11 | # string modulo operator(%) to print # print integer and float value print("Vishesh : % 2d, Portal : % 5.2f" %(1, 05.333)) # print integer value print("Total students : % 3d, Boys : % 2d" %(240, 120)) # print octal value print("% 7.3o"% (25)) # print exponential value print("% 10.3E"% (356.08977)) |
Output:
Python uses C-style string formatting to create new, formatted strings. The “%” operator is used to format a set of variables enclosed in a “tuple” (a fixed size list), together with a format string, which contains normal text together with “argument specifiers”, special symbols like “%s” and “%d”.
Example:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 | # This prints out "Hello, John!" name = "John" print("Hello, %s!" % name) # This prints out "John is 23 years old." name = "John" age = 23 print("%s is %d years old." % (name, age)) # This prints out: A list: [1, 2, 3] mylist = [1,2,3] print("A list: %s" % mylist) |
Output:
1 2 3 4 5 6 | Hello, John! John is 23 years old. A list: [1, 2, 3] >>> |