5ol.cc 发表于 2017-5-1 10:13:40

Python 格式化字符串小练习

Python 格式化字符串小练习
1,代码:
 view plaincopyprint?



[*]#coding:utf-8  
[*]  
[*]#字符串格式化示例  
[*]#使用给定的宽度打印格式化后的价格列表  
[*]  
[*]#-------------------------------------------------------------  
[*]# 1,使用星号(*)作为字符宽度或者精度(或者两者都使用*),此时数值会从元祖参数中读出:  
[*]#   如:  
[*]#    >>> '%.*s' % (5,'Guido van Rossum')  
[*]#    'Guido'  
[*]#    >>> '%.*s' % (9,'Guido van Rossum')  
[*]#    'Guido van'  
[*]#2,减号(-)用来左对齐数值  
[*]#    >>> from math import pi  
[*]#    >>> '%-10.2f' % pi  
[*]#    '3.14      '  
[*]#    >>> '%10.2f' % pi  
[*]#    '      3.14'  
[*]#    >>> '%+10.2f' % pi  
[*]#    '     +3.14'  
[*]#3,空白('')意味着在正数前加上空格,在需要对齐正负数时会很有用:  
[*]#    >>> print ('% 5d' % 10) + '\n' + ('% 5d' % -10)  
[*]#       10  
[*]#      -10  
[*]#4,加号(+)表示不管是正数还是负数都标示出符号  
[*]#    >>> print ('%+5d' % 10) + '\n' + ('%+5d' % -10)  
[*]#      +10  
[*]#      -10  
[*]#-----------------------------------------------------------  
[*]  
[*]width = input('请输入表格的宽度:')  
[*]  
[*]price_width = 10  
[*]item_width = width - price_width  
[*]  
[*]header_format = '%-*s%*s'  
[*]format = '%-*s%*.2f'  
[*]  
[*]print '='*width  
[*]  
[*]#打印表头  
[*]print header_format %(item_width,'项目',price_width,'价格')  
[*]  
[*]print '-' * width  
[*]  
[*]print format % (item_width,'苹果',price_width,6.0)  
[*]print format % (item_width,'桔子',price_width,3.2)  
[*]print format % (item_width,'香蕉',price_width,2.5)  
[*]print format % (item_width,'葡萄',price_width,14.8)  
[*]print format % (item_width,'红提',price_width,15)  
[*]print format % (item_width,'西瓜',price_width,1.5)  
[*]  
[*]print '='*width  


2,输出结果:
 view plaincopyprint?



[*]请输入表格的宽度:30  
[*]==============================  
[*]项目                  价格  
[*]------------------------------  
[*]苹果                    6.00  
[*]桔子                    3.20  
[*]香蕉                    2.50  
[*]葡萄                   14.80  
[*]红提                   15.00  
[*]西瓜                    1.50  
[*]==============================  
页: [1]
查看完整版本: Python 格式化字符串小练习