Format() Function in Python

Definition : 

The format function is used for printing a certain type of value held within the second bracket.

Syntax : 

print( " STATEMENT .....{}.....STATEMENT.....".format(<variable name>/ <value>)) 

Important things to remember :-

1. If we use a variable name, we should leave the brackets empty {}, rather than {<variable name>}.

2.Not only variables we can also replace constants for example : - print("Hello {word}".format(word = "world")), we will get the output as " Hello world ".

3. We can also leave the {} empty rather than replacing by a constant. For example print(" Hello {} ".format("World")), this will also give the output as " Hello world"

Program in Online Compiler


Formatting Types

Inside the placeholders you can add a formatting type to format the result:

:<Try itLeft aligns the result (within the available space)
:>Try itRight aligns the result (within the available space)
:^Try itCenter aligns the result (within the available space)
:=Try itPlaces the sign to the left most position
:+Try itUse a plus sign to indicate if the result is positive or negative
:-Try itUse a minus sign for negative values only
Try itUse a space to insert an extra space before positive numbers (and a minus sign befor negative numbers)
:,Try itUse a comma as a thousand separator
:_Try itUse a underscore as a thousand separator
:bTry itBinary format
:cConverts the value into the corresponding unicode character
:dTry itDecimal format
:eTry itScientific format, with a lower case e
:ETry itScientific format, with an upper case E
:fTry itFix point number format
:FTry itFix point number format, in uppercase format (show inf and nan as INF and NAN)
:gGeneral format
:GGeneral format (using a upper case E for scientific notations)
:oTry itOctal format
:xTry itHex format, lower case
:XTry itHex format, upper case
:nNumber format
:%Try itPercentage format


Comments

Popular posts from this blog

Bubble Sort ( C & Python 3)

Comparison Logical and Bitwise Operator ( Java Part - 4 )

Something about me