Catalog | Previous section (2.2 Containers ) | [ Next section (2.4 Sequence )]()
2.3 format
Although this section is a little off topic , But when dealing with data , You usually want to generate structured output ( Such as the table ). Example :
Name Shares Price
---------- ---------- -----------
AA 100 32.20
IBM 50 91.10
CAT 150 83.44
MSFT 200 51.23
GE 95 40.37
MSFT 50 65.10
IBM 100 70.44
String formatting
stay Python 3.6+ in , One way to format a string is to use f-strings
:
>>> name = 'IBM'
>>> shares = 100
>>> price = 91.1
>>> f'{name:>10s} {shares:>10d} {price:>10.2f}'
' IBM 100 91.10'
>>>
{expression:format}
Part of it will be replaced .
f-strings
Usually and print()
Functions together :
print(f'{name:>10s} {shares:>10d} {price:>10.2f}')
Format code
Format code ( stay {}
Inside :
after ) And C Linguistic printf()
Function similar to . Common format codes include :
d Decimal integer
b Binary integer
x Hexadecimal integer
f Float as [-]m.dddddd
e Float as [-]m.dddddde+-xx
g Float, but selective use of E notation
s String
c Character (from integer)
Common modifiers can adjust the precision of field width and number . This is part of it :
:>10d Integer right aligned in 10-character field
:<10d Integer left aligned in 10-character field
:^10d Integer centered in 10-character field
:0.2f Float with 2 digit precision
Dictionary formatting
You can use string format_map()
Method applies string formatting to the dictionary of values :
>>> s = {
'name': 'IBM',
'shares': 100,
'price': 91.1
}
>>> '{name:>10s} {shares:10d} {price:10.2f}'.format_map(s)
' IBM 100 91.10'
>>>
although format_map()
and f-strings
Use the same format code , But get the value from the dictionary provided .
format() Method
There is one format()
Method can apply formatting to parameters or keyword parameters :
>>> '{name:>10s} {shares:10d} {price:10.2f}'.format(name='IBM', shares=100, price=91.1)
' IBM 100 91.10'
>>> '{:10s} {:10d} {:10.2f}'.format('IBM', 100, 91.1)
' IBM 100 91.10'
>>>
Frankly speaking ,format()
The method is a little bit lengthy , I prefer to use f-strings.
C Style formatting
You can also use formatting operators %
:
>>> 'The value is %d' % 3
'The value is 3'
>>> '%5d %-5d %10d' % (3,4,5)
' 3 4 5'
>>> '%0.2f' % (3.1415926,)
'3.14'
This requires a single or tuple on the right , Format codes are also imitations C Language printf()
Functional .
Be careful : This is the only formatting method available on byte strings .
>>> b'%s has %n messages' % (b'Dave', 37)
b'Dave has 37 messages'
>>>
practice
practice 2.8: How to format numbers
A common problem in printing numbers is to specify the number of decimal places . One of the solutions is to use f-strings. Please try the following example :
>>> value = 42863.1
>>> print(value)
42863.1
>>> print(f'{value:0.4f}')
42863.1000
>>> print(f'{value:>16.2f}')
42863.10
>>> print(f'{value:<16.2f}')
42863.10
>>> print(f'{value:*>16,.2f}')
*******42,863.10
>>>
of f-strings The full documentation of the format code used in here Can find . Sometimes , Also use string operators %
Perform formatting .
>>> print('%0.4f' % value)
42863.1000
>>> print('%16.2f' % value)
42863.10
>>>
And operators %
Documents related to various format codes used can be found in here find . Although it is usually related to print()
Functions together , But string formatting has nothing to do with printing . If you want to save the formatted string , Just assign it to a variable .
>>> f = '%0.4f' % value
>>> f
'42863.1000'
>>>
practice 2.9: collecting data
In practice 2.7 in , Write a program to calculate the profit and loss of stock investment report.py
. In this exercise , You need to modify this program to generate the following table :
Name Shares Price Change
---------- ---------- ---------- ----------
AA 100 9.22 -22.98
IBM 50 106.28 15.18
CAT 150 35.46 -47.98
MSFT 200 20.89 -30.34
GE 95 13.48 -26.89
MSFT 50 20.89 -44.21
IBM 100 106.28 35.84
In this table ,"Price" It's the current stock price ,"Change" It's the difference between the current share price and the original purchase price .
To generate the above table , First you need to collect all the data shown in the table . To write make_report()
function , Take stock list and price dictionary as input , And returns a tuple list containing all the rows in the above table .
hold make_report()
Function added to report.py
In file . If the function is executed interactively , The following steps should be followed :
>>> portfolio = read_portfolio('Data/portfolio.csv')
>>> prices = read_prices('Data/prices.csv')
>>> report = make_report(portfolio, prices)
>>> for r in report:
print(r)
('AA', 100, 9.22, -22.980000000000004)
('IBM', 50, 106.28, 15.180000000000007)
('CAT', 150, 35.46, -47.98)
('MSFT', 200, 20.89, -30.339999999999996)
('GE', 95, 13.48, -26.889999999999997)
...
>>>
practice 2.10: Print the formatted form
Redo the exercise 2.9 Medium for loop , But change the print statement to format the ancestor .
>>> for r in report:
print('%10s %10d %10.2f %10.2f' % r)
AA 100 9.22 -22.98
IBM 50 106.28 15.18
CAT 150 35.46 -47.98
MSFT 200 20.89 -30.34
...
>>>
You can also use f-strings Extended value . for example :
>>> for name, shares, price, change in report:
print(f'{name:>10s} {shares:>10d} {price:>10.2f} {change:>10.2f}')
AA 100 9.22 -22.98
IBM 50 106.28 15.18
CAT 150 35.46 -47.98
MSFT 200 20.89 -30.34
...
>>>
Add the above statement to report.py
In the program , Let the program get make_report()
Output , And print the formatted table as shown in the figure above .
practice 2.11: Add the title
Suppose there is a tuple of Title names like the following :
headers = ('Name', 'Shares', 'Price', 'Change')
Add the title tuple code above to the program , And create a string , Each heading is aligned to the right and the width is 10, Each field is separated by a single space .
' Name Shares Price Change'
Write code to create a separate string between the title and the data . A separator string is a string of underscores under each field name ("-") character . for example :
'---------- ---------- ---------- -----------'
When finished , The program should generate the table shown at the top of this section .
Name Shares Price Change
---------- ---------- ---------- ----------
AA 100 9.22 -22.98
IBM 50 106.28 15.18
CAT 150 35.46 -47.98
MSFT 200 20.89 -30.34
GE 95 13.48 -26.89
MSFT 50 20.89 -44.21
IBM 100 106.28 35.84
practice 2.12: Format challenge
How to modify the code so that the price includes the currency symbol ($), And output like this :
Name Shares Price Change
---------- ---------- ---------- ----------
AA 100 $9.22 -22.98
IBM 50 $106.28 15.18
CAT 150 $35.46 -47.98
MSFT 200 $20.89 -30.34
GE 95 $13.48 -26.89
MSFT 50 $20.89 -44.21
IBM 100 $106.28 35.84
Catalog | Previous section (2.2 Containers ) | [ Next section (2.4 Sequence )]()
notes : See... For the complete translation https://github.com/codists/practical-python-zh