String Formatting in Python

String Formatting:

String Formatting in Python is one of the exciting features. The % operator takes a format string on the left (%d, %s, %f, etc) and the corresponding values in a tuple on the right. The format operator % allows users to construct strings, replacing parts of the strings with the data stored in variables. It has the following syntax:

"" % ()

The statement begins with a format string consisting of a sequence of characters and conversion specifications.

Conversion Specifications start with a % operator and can appear anywhere within the string. Following the format string is a % sign and then a set of values, one per conversion specification, separated by commas and enclosed in parenthesis. If there is a single value then parenthesis is optional.

Example:

name="Rani"
age=8
print("Name= %s and Age= %d" %(name, age))

Output:
Name= Rani and Age= 8

Format SymbolPurpose
%cCharacter
%dSigned Decimal Integer
%sString
%uUnsigned Decimal Integer
%oOctal Integer
%xHexadecimal Integer
%eExponential Notation
%fFloating-Point Number
%gShort Numbers in Floating-Point

Program:

i=1
print("i\t1**2\t1**3\t1**4\t1**5")
while i<=5:
print(i, '\t', i**2, '\t', i**3, '\t', i**5, '\t', i**10)
i+=1

Output:
String Formatting in Python