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:
:< | Left aligns the result (within the available space) | |
:> | Right aligns the result (within the available space) | |
:^ | Center aligns the result (within the available space) | |
:= | Places the sign to the left most position | |
:+ | Use a plus sign to indicate if the result is positive or negative | |
:- | Use a minus sign for negative values only | |
: | Use a space to insert an extra space before positive numbers (and a minus sign befor negative numbers) | |
:, | Use a comma as a thousand separator | |
:_ | Use a underscore as a thousand separator | |
:b | Binary format | |
:c | Converts the value into the corresponding unicode character | |
:d | Decimal format | |
:e | Scientific format, with a lower case e | |
:E | Scientific format, with an upper case E | |
:f | Fix point number format | |
:F | Fix point number format, in uppercase format (show inf and nan as INF and NAN ) | |
:g | General format | |
:G | General format (using a upper case E for scientific notations) | |
:o | Octal format | |
:x | Hex format, lower case | |
:X | Hex format, upper case | |
:n | Number format | |
:% | Percentage format |
Comments
Post a Comment