官术网_书友最值得收藏!

  • Learn Python in 7 Days
  • Mohit Bhaskar N. Das
  • 235字
  • 2021-07-09 20:40:22

Formatted output

Consider an example where you would want to print the name, marks, and the age of the person:

print "Name", "Marks", "Age" 
print "John Doe", 80.67, "27"
print "Bhaskar", 76.908, "27"
print "Mohit", 56.98, "25"

The output will be as follows:

C:pydev>python hello.py
Name Marks Age
John Doe 80.67 27
Bhaskar 76.908 27
Mohit 56.98 25

You can see the output, but the output that is displayed is not formatted. Python allows you to set the formatted output. If you have done some coding in C language, then you should be familiar with %d, %f, %sIn order to represent an integer %d is used, %f is used for float, and %s is used for string. If you used %5d, it means 5 spaces. If you used %5.2f, it means 5 spaces and .2 means precision. The decimal part of the number or the precision is set to 2. Let's use the formatting on the preceding example:

print "Name Marks Age" 
print ( "%s %14.2f %11d" % ("John Doe", 80.67, 27))
print ( "%s %12.2f %11d" %("Bhaskar" ,76.901, 27))
print ( "%s %3.2f %11d" %("Mohit", 56.98, 25))

The output we get is as follows:

C:pydev>python hello.py
Name Marks Age
John Doe 80.67 27
Bhaskar 76.90 27
Mohit 56.98 25

The preceding output is much better than the previous one. You can see Marks 76.901 set to 76.90 automatically.

主站蜘蛛池模板: 临沭县| 大方县| 远安县| 陆川县| 龙游县| 达拉特旗| 屏东市| 大埔县| 富蕴县| 静安区| 蒲江县| 吉木乃县| 大竹县| 灯塔市| 中牟县| 宜章县| 玛沁县| 兰考县| 龙泉市| 大安市| 文安县| 河间市| 景谷| 宁蒗| 淮阳县| 南漳县| 盘锦市| 宁南县| 镇平县| 泉州市| 景东| 舞阳县| 新平| 资阳市| 肇源县| 景谷| 麻城市| 青龙| 沾化县| 桂平市| 塘沽区|