Another useful Type Specifying
- %u unsigned decimal integer
- %o octal integer
- f – floating-point display
- b – binary number
- o – octal number
- %x – hexadecimal with lowercase letters after 9
- %X– hexadecimal with uppercase letters after 9
- e – exponent notation
You can also specify formatting symbols. The only change is using a colon (:) instead of %.
For example, instead of %s use {:s} and instead of %d use (:d}
Syntax : String {field_name:conversion} Example.format(value)
Errors and Exceptions :
ValueError : Error occurs during type conversion in this method.
Convert base-10 decimal integers to floating-point numeric constants
Python3
print ( "This site is {0:f}% securely {1}!!" . format ( 100 , "encrypted" )) # To limit the precision print ( "My average of this {0} was {1:.2f}%" . format ( "semester" , 78.234876 )) # For no decimal places print ( "My average of this {0} was {1:.0f}%" . format ( "semester" , 78.234876 )) # Convert an integer to its binary or # with other different converted bases. print ( "The {0} of 100 is {1:b}" . format ( "binary" , 100 )) print ( "The {0} of 100 is {1:o}" . format ( "octal" , 100 )) |
Output
This site is 100.000000% securely encrypted!!
My average of this semester was 78.23%
My average of this semester was 78%
The binary of 100 is 1100100
The octal of 100 is 144
Python String format() Method
The format()
method is a powerful tool that allows developers to create formatted strings by embedding variables and values into placeholders within a template string. This method offers a flexible and versatile way to construct textual output for a wide range of applications. Python string format() function has been introduced for handling complex string formatting more efficiently. Sometimes we want to make generalized print statements in that case instead of writing print statements every time we use the concept of formatting.