Menu Close

Python format() Function

Python format() function

In this Python built-in function tutorial, we are going to learn all about the Python format function that is used to format the specified value into the specified format. format function in Python support various format.

Python format() function

The Python format() function is a Python built-in function which means you don’t need to install it or import it from another module because it comes with Python by default. To use the format function in Python, you should provide two values first will be the value to be formatted, and second will be the format which you want to format to.

Syntax

The syntax of the format function in python is:-

format(value, format)

Return Value

Python format method returns a formatted value.

Parameter

Python format method supports two parameters.

  • value:- Value of any format.
  • format:- The format you want to format the value.

You can use the following format to format the value.

FormatDescription
‘<‘Left aligns the result
‘>’Right aligns the result.
‘^’The Center aligns the result.
‘=’Place the sign in the leftmost position.
‘+’Use the plus sign to indicate if the result is positive or negative.
‘-‘Use minus sign for negative results only.
‘ ‘Use leading space for positive numbers.
‘,’Use a comma as a thousand separator.
‘_’Use an underscore as a thousand separator.
‘b’Binary format.
‘c’Converts the value to the corresponding Unicode characters.
‘d’Decimal format.
‘e’Scientific format. with a lowercase e
‘E’Scientific format. with a lowercase E
‘f’fix point number format.
‘F’fix point number format.
‘g’General format.
‘G’General format.
‘o’Octal format.
‘X’Hex format.
‘n’Number format.
‘%’Percentage format.

Python format() Function Exmaple

Here we have used the Python format method along with an example.

Example:


#Convert 150 into binary
print(format(150, 'b'))

#Convert 10 into octal format
print(format(10, 'o'))

#convert 150 into scientific format
print(format(150, 'e'))

#Convert 150 into hexadecimal
print(format(150, 'x'))

#Convert 150 into generl format
print(format(150, 'g'))

#Convert 100 into percent.
print(format(100, '%'))

#Convert 112 into number
print(format(112, 'n'))

#Convert 150 into float.
print(format(150, 'f'))

Output

10010110
12
1.500000e+02
96
150
10000.000000%
112
150.000000

Conclusion

So, Here we have learned all about the Python format method to format the specified value into the specified format.
If this article is helpful for you, please keep visiting for further python built-in functions tutorials.

Other Python built-in functions


For more information:- Click Here

Python enumerate() Function
Python frozenset Function

Related Posts