0% found this document useful (0 votes)
10 views6 pages

Handout 5 Format Function

Uploaded by

shivaniganji45
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
10 views6 pages

Handout 5 Format Function

Uploaded by

shivaniganji45
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd

Handout-5

Format () function
Formatting Numbers
1. Python built-in format () function, you pass two arguments to the function:
 a numeric value
 And a format specifier: The format specifier is a string that contains special
characters specifying how the numeric value should be formatted.
Example:
 format(12345.6789, '.2f')

2. The first argument, the floating-point number 12345.6789, is the number we want to
format. The second argument, which is the string '.2f', is the format specifier.
 >>> print(format(12345.6789, '.2f'))
12345.68

3. Here is the meaning of its contents:


• The .2 specifies the precision. It indicates that we want to round the number to two
decimal places.
• The f specifies that the data type of the number we are formatting is a floating-point
number.

4. When a floating-point number is displayed by the print function, it can appear with up to
12 significant digits.

 # Program demonstrates how a floating-point number is displayed with no


formatting.
amount_due = 5000.0
monthly_payment = amount_due / 12.0
print ('The monthly payment is', monthly_payment)

5. Because this program displays a dollar amount, it would be nice to see that amount rounded
to two decimal places. Fortunately, Python gives us a way to do just that, and more, with the
built-in format function
 # Program demonstrates how a floating-point number can be formatted.
amount_due = 5000.0
monthly_payment = amount_due / 12
print('The monthly payment is', format(monthly_payment, '.2f'))
 # Program demonstrates how a floating-point number can be displayed as currency.
monthly_pay = 5000.0
annual_pay = monthly_pay * 12
print('Your annual pay is $',format(annual_pay, ',.2f'), sep='')

#Another EXAMPLE

 # This program displays the following floating-point numbers in a column with their
decimal points aligned.
num1 = 127.899
num2 = 3465.148
num3 = 3.776
num4 = 264.821
num5 = 88.081
num6 = 799.999
# Display each number in a field of 7 spaces with 2 decimal places.

print(format(num1, '7.2f'))
print(format(num2, '7.2f'))
print(format(num3, '7.2f'))
print(format(num4, '7.2f'))
print(format(num5, '7.2f'))
print(format(num6, '7.2f'))
Formatting in Scientific Notation:
1. If you prefer to display floating-point numbers in scientific notation, you can use the letter
e or the letter E instead of f. Here are some examples:
 >>> print(format(12345.6789, 'e'))
1.234568e+04
2. The first statement simply formats the number in scientific notation. The number is displayed
with the letter e indicating the exponent
 >>> print(format(12345.6789, '.2e'))
1.23e+04 # The second statement additionally specifies a precision of two decimal places.

Inserting Comma Separators


1. If you want the number to be formatted with comma separators, you can insert a comma into
the format specifier, as shown here:
 >>> print(format(12345.6789, ',.2f'))
12,345.68
Specifying a Minimum Field Width:

1. The format specifier can also include a minimum field width, which is the minimum number of
spaces that should be used to display the value. The following example prints a number in a field
that is 12 spaces wide with two decimal places.

 >>> print('The number is', format(12345.6789, '12,.2f'))


The number is 12,345.68
#The following example prints a number in a field that is 20 spaces wide with three
decimal places
>>> print('The number is', format(12345.6789, '20,.3f'))
The number is 12,345.679
Formatting a Floating-Point Number as a Percentage:
1. Instead of using f as the type designator, you can use the % symbol to format a floating-point
number as a percentage. The % symbol causes the number to be multiplied by 100 and displayed
with a % sign following it.
Example:
 >>> print(format(0.5, '%'))
50.000000%
>>>
 Here is an example that specifies 0 as the precision:
>>> print(format(0.5, '.0%'))
50%
>>>
Formatting Integers:

1. You can also use the format function to format integers. There are two differences to keep in
mind when writing a format specifier that will be used to format an integer:

• You use d as the type designator.


• You cannot specify precision.
 Examples.
 # In the following session, the number 123456 is printed with no special formatting:
>>> print(format(123456, 'd'))
123456
>>>
#In the following session, the number 123456 is printed with a comma separator:
>>> print(format(123456, ',d'))
123,456
>>>
 # Here, we format an integer formatted_age as a zero-padded string with a width of
3.
>>>age = 30
>>>formatted_age = format(age, "03d")
>>>print(formatted_age) # Output: "030"
>>>030
 Here, we format an integer formatted_age as a zero-padded string with a width of
3.
>>> age = 30
>>> formatted_age = format(age, "02d")
>>> print(formatted_age) # Output: "03"
>>>30

 In the following session, the number 123456 is printed in a field that is 10 spaces
wide:
>>> print(format(123456, '10d'))
123456
In the following session, the number 123456 is printed in a field that is 20 spaces
wide:
>>> print(format(123456, '20d'))
123456
 #In the following session, the number 123456 is printed with a comma separator in
a field that is 10 spaces wide:
>>> print(format(123456, '10,d'))
123,456
 #In the following session, the number 123456 is printed with a comma separator in
a field that is 20 spaces wide:
>>> print(format(123456, '20,d'))
123,456
Formatting Strings
The `format()` method, allows you to insert values into placeholders within a string.
Here are some examples of how to use the `format ()` method for string formatting:

1. Basic String Formatting:


name = "RAM"
age = 30
formatted_string = "My name is {} and I am {} years old.".format(name, age)
print(formatted_string)
# Output: " My name is RAM and I am 30 years old."

In the above example, `{}` curly braces serve as placeholders for variables, and the
`format()` method replaces them with the values of `name` and `age`.

2. Using Indexed Placeholders:


item = "apple"
quantity = 5
price = 0.5
formatted_string = "You bought {0} {1}s at ${2:.2f} each.".format(quantity, item,
price)
print(formatted_string)
# Output: "You bought 5 apples at $0.50 each."

Above example, indexed placeholders `{0}`, `{1}`, and `{2}` to specify the order of
variables to be inserted.

item = "apple"
quantity = 5
price = 0.5
formatted_string = "You bought {0} {1}s at ${2:.1f} each.".format(quantity, item,
price)
print(formatted_string)
# Output: You bought 5 apples at $0.5 each.
4. Formatting Numbers within the String:
value = 12345.6789
formatted_string = "The value is {:.2f}".format(value)
print(formatted_string)
# Output: "The value is 12345.68"
In this case, we format the floating-point number within the string with two decimal
places.

5. Aligning Text:
text = "Hello"
>>> formatted_string = "{:>20}".format(text)
>>> print(formatted_string)
Hello
>>> formatted_string = "{:<20}".format(text)
>>> print(formatted_string)
Hello
>>> formatted_string = "{:^20}".format(text)
>>> print(formatted_string)
Hello
You can specify alignment using `<` for left, `>` for right, or `^` for centre alignment
within the placeholders.

6. F-strings:
name = "RAM"
age = 35
formatted_string = f"My name is {name} and I am {age} years old."
print(formatted_string)
# Output: "My name is RAM and I am 35 years old."

F-strings provide a more concise and readable way to format strings in Python 3.6
and later.

You might also like