Menu Close

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.
In the previous tutorial, we have seen, python filter function to filter each item of the iterable through a function.

Python format() function

The Python format function is a Python built-in function that is used to format the specified value into the specified format.

Syntax

The syntax of format function in python is:-

format(value, format)

Return Value

Python format method returns formatted value.

Parameter

Python format method support two parameters.

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

You can use following format to format the value.

FormatDescription
‘<‘Left aligns the result
‘>’Right aligns the result.
‘^’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 result only.
‘ ‘Use leading space for positive numbers.
‘,’Use a comma as a thousands 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 lower case e
‘E’Scientific format. with a lower case 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 exmaple

Here we have used Python format method along with 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 helpful for you, please keep visiting for further python built-in functions tutorial.

Other Python built-in functions

For more information:- Click Here

Python frozenset Function
Python getattr() Function

Was this post helpful?

Related Posts

Leave a Reply

Your email address will not be published. Required fields are marked *