先看代碼吧。
#!/usr/bin/env python#-*- coding: utf-8 -*-__author__ = 'jiang'__creattime__ = '2015/10/31 23:40'width = input('please enter width:')PRice_width = 10item_width = width - price_widthheader_format = '%-*s%*s'format = '%-*s%*.2f'print '=' * widthprint header_format % (item_width,'Item',price_width,'Price')print '-' * widthprint format % (item_width,'Apples',price_width,0.4)print format % (item_width,'Pears',price_width,0.5)print format % (item_width,'Cantaloupes',price_width,1.92)print format % (item_width,'Dried Apricots(16 oz.)',price_width,8)print format % (item_width,'Prunes(4 lbs)',price_width,12)print '=' * widthok,再讓我們看看打印出來(lái)是什么樣的。
==================================================Item Price--------------------------------------------------Apples 0.40Pears 0.50Cantaloupes 1.92Dried Apricots(16 oz.) 8.00Prunes(4 lbs) 12.00==================================================
看著還行,不過(guò)有個(gè)問(wèn)題,在你給width賦值的時(shí)候盡量大一點(diǎn)。如果你賦值太小比如20,右邊的價(jià)格就不會(huì)對(duì)齊。有興趣的可以跑一邊代碼。
說(shuō)幾個(gè)關(guān)鍵的點(diǎn)。head_format = '%-*S%*s' ,字符串格式操作符%后面加s表示可以使用str格式化任意python對(duì)象。'-'表示左對(duì)齊。'*'表示可以接收字段寬度和精度。
下面是字符串格式化轉(zhuǎn)換類型,或許你可以看看。
轉(zhuǎn)換類型 含義d,i 帶符號(hào)的十進(jìn)制整數(shù)o 不帶符號(hào)的八進(jìn)制u 不帶符號(hào)的十進(jìn)制x 不帶符號(hào)的十六進(jìn)制(小寫(xiě))X 不帶符號(hào)的十六進(jìn)制(大寫(xiě))e 科學(xué)計(jì)數(shù)法表示的浮點(diǎn)數(shù)(小寫(xiě))E 科學(xué)計(jì)數(shù)法表示的浮點(diǎn)數(shù)(大寫(xiě))f,F 十進(jìn)制浮點(diǎn)數(shù)r 字符串(使用repr轉(zhuǎn)換任意python對(duì)象)s 字符串(使用str轉(zhuǎn)換任意python對(duì)象)
關(guān)于更多的字符串轉(zhuǎn)換類型你可以去網(wǎng)上搜索一下。
簡(jiǎn)單的轉(zhuǎn)換:
>>>'Price of eggs : $%d' % 42'Price of eggs : $42'>>>from math import pi>>>'Pi : %f...' % piPi : 3.141593...>>>'my age is %s ' % 42L'my age is 42'>>>'my age is %r' % 42L'my age is 42L'
關(guān)于str和repr的區(qū)別,各位可以去搜索一下,我這里就不贅述了。
新聞熱點(diǎn)
疑難解答
圖片精選
網(wǎng)友關(guān)注