Translation: practical Python Programming 02_ 03_ Formatting

codists 2021-02-23 00:12:46
translation practical python programming 02_


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

版权声明
本文为[codists]所创,转载请带上原文链接,感谢
https://pythonmana.com/2021/02/20210222160128500Z.html

  1. Python 空间绘图 - 房价气泡图绘制
  2. Translation: practical Python Programming 02_ 02_ Containers
  3. Research on Portfolio Optimization Based on particle swarm optimization
  4. Ubuntu deploying Django project
  5. Two years of Java, write Python and go without byte beating
  6. Translation: practical Python Programming 02_ 02_ Containers
  7. So learn python, grandfather learned! Introduction to super simple Python
  8. python3 多线程 与 mongo亿级消费日志数据 新鲜demo 【优化第一版】
  9. Summary of Chinese word segmentation based on Jieba
  10. I've heard it n times, but I'm not impressed. After reading this, you'll understand
  11. Summary of Chinese word segmentation based on Jieba
  12. From movie art to Python code to realize God's reverse thinking mode
  13. Summary of Chinese word segmentation based on Jieba
  14. ARIMA模型预测CO2浓度时间序列-python实现
  15. Python belongs to back-end development or front-end development? Introduction to Python!
  16. python isinstance()
  17. I've heard it n times, but I'm not impressed. After reading this, you'll understand
  18. This article will familiarize you with the transformation process of Python - & gt; cafe - & gt; om model
  19. 如何用Python一键修改上万个文件名
  20. One day quick start to Python
  21. Python 学习笔记: List
  22. 翻译:《实用的Python编程》02_03_Formatting
  23. Is there any age requirement for learning Python? Is 30 OK?
  24. Professor Tsinghua! The most complete Python tutorial in 12 hours (free sharing at the end of the article)
  25. Using Python to develop defi project
  26. Detailed explanation of Python function
  27. Python 可变类型作为函数默认参数时的副作用
  28. What do Python engineers do? What's their future?
  29. 这是我见过最好的Python教程:十分钟带你认识Python
  30. Python欢喜冤家:爬虫与反爬虫带着处理方案来给大家拜年了
  31. Python - zip() function
  32. 写Python会遇到如下的错误:ModuleNotFoundError: No module named 'email.mime'; 'email' is not a package
  33. Python类的调用以及私有和公有属性方法的调用
  34. Python类的专有方法
  35. Python基础之:数字字符串和列表
  36. How did Python pioneers evaluate this language on their 30th birthday?
  37. Python基础之:数字字符串和列表
  38. Python基础之:数字字符串和列表
  39. 窥探未来不是梦,python数据分析轻松实现
  40. This article will familiarize you with the transformation process of Python - & gt; cafe - & gt; om model
  41. 阿里、华为Python工程师总结的实用技巧,只有你还没看?
  42. 酸了!看到抖音上Python程序员晒得工资条......
  43. Python基础之:数字字符串和列表
  44. Importing excel into database adaptively by Python
  45. Python安装教程
  46. Python安装教程
  47. From Xiaobai to master, here is a guide to pandas
  48. [Python] drawing method of stem leaf diagram and compound pie diagram
  49. Drawing of Python geoplot spatial kernel density estimation map
  50. Python Seaborn economist's classic chart imitation
  51. Python space drawing - regionmask mask operation example
  52. Python space drawing - cartopy longitude and latitude add
  53. Python pykrige package Kriging interpolation calculation and visual rendering
  54. Python batch resampling, mask, slope extraction
  55. Python - Analysis of reachable circle of multiple traffic modes
  56. Python space drawing bubble drawing
  57. Python 3 multithreading and Mongo 100 million consumption log data fresh demo
  58. ARIMA model for predicting time series of CO2 concentration
  59. python isinstance()
  60. How to modify tens of thousands of file names with one key in Python