89DEVs

Python: format() function

format() overview

The format() function in Python returns a formatted representation of a given value. The format can be specified in the format specifications, which can be passed to the format() function as the second argument.

format() format types

The format() function can format the value in a variety of different types. The following table gives an overview of the formatting types and the flags used in the second argument of the format() function.
flag format type
d decimal integer
c unicode character
b binary
o octal
x hexadecimal - lower case
d hexadecimal - upper case
n decimal integer, separator in current locale
e exponential - lower case
E exponential - upper case
f fixed point number - default 6
F fixed point number - shows inf as INF and nan as NAN
g rounds number to specified digits - default 6
G rounds number to specified digits - switches to E for large numbers
% percentage

format() as binary

To format a number as binary representation, use the b flag as the second argument of the format() function. # format() number as binary myInt = 25 myBin = format(myInt, 'b') print(myBin) The number is formatted to binary format. The result is equal to the result of the bin() function. However, no prefix is added by the format() function. 11001

format() syntax

The syntax of the format() function is: format(object[, format_specifications])

format() arguments

The format() function accepts between 1 and 2 arguments. The first argument is required and represents the object to be formatted. The second argument is optional and allows specifications on how the value has to be formatted. Use the format types to specify the format to be used.

format() return values

The format() function returns a formatted representation of the given object. The exact format can be specified in the second argument.

                
        

Summary


Click to jump to section