| >>> text = '%d %.2f %s' % (1, 99.3, 'Justin') >>> print(text) 1 99.30 Justin >>> print('%d %.2f %s' % (1, 99.3, 'Justin')) 1 99.30 Justin >>> |
格式化字串時,所使用的%d、%f、%s等 與C語 言類似,之後使用%接上一個tuple, 也就是範例中以()包 括的實字表示部份。一些可用的字串格式字列舉如下:
| %% | 在字串 中顯示% |
| %d | 以10 進位整數方式輸出 |
| %f | 將浮點 數以10進位方式輸出 |
| %e, %E | 將浮點 數以10進位方式輸出,並使用科學記號 |
| %o | 以8進 位整數方式輸出 |
| %x, %X | 將整 數以16進位方式輸出 |
| %s | 使用str()將字串輸出 |
| %c | 以字元 方式輸出 |
| %r | 使用repr()輸 出字串 |
可以在輸出浮點數時指定精度,例如:
| >>> 'example:%.2f' % 19.234'example:19.23' >>> |
也可以指定輸出時,至少要預留的字元寬度,例如:
| >>> "example:%6.2f" % 19.234'example: 19.23' >>> |
由於預留了6個字元寬度,不足的部份要由空白字元補上。使用%運算子來格式化字串,會產生新的字串物件。
在格式化時,也可以使用關鍵字來指定,例如:
| >>> '%(real)s is %(nick)s!!' % ({'real' : 'Justin', 'nick' : 'caterpillar'})'Justin is caterpillar!!' >>> |
實際上,以上的字串格式化方式是舊式的作法,在未來的Python版本中可能不再支援這種作法,若有更進一步的興趣了解,可以參考 Old String Formatting Operations。
在Python3(或Python 2.6)中導入了新的格式化字串方法,可以讓你根據位置、關鍵字(或兩者混合)來進行字串格式化,例如:
| >>> '{0} is {1}!!'.format('Justin', 'caterpillar')'Justin is caterpillar!!' >>> '{real} is {nick}!!'.format(real = 'Justin', nick = 'caterpillar')'Justin is caterpillar!!' >>> '{real} is {nick}!!'.format(nick = 'caterpillar', real = 'Justin')'Justin is caterpillar!!' >>> '{0} is {nick}!!'.format('Justin', nick = 'caterpillar')'Justin is caterpillar!!' >>> '{name} is {age} years old!'.format(name = 'Justin', age = 35) 'Justin is 35 years old!' >>> |
以上是最基本的格式化作法,你可以在字串中使用{}包括位罝索引或關鍵字,並使用format()方法來指定實際上位置索引或關鍵字真正的值。format()會產生新的字串,為結合引數的格式化結果字串。
如果要存取format()中指定物件的屬性,或者是所指定物件是個字典、串列物件,則上在{}中包括的索引或關鍵字,可以代表即將指定的物件。例如:
| >>> import math >>> 'PI = {0.pi}'.format(math)'PI = 3.14159265359' >>> import sys >>> 'My platform is {pc.platform}'.format(pc = sys)'My platform is win32' >>> 'My platform is {0.platform}. PI = {1.pi}.'.format(sys, math) 'My platform is win32. PI = 3.14159265359.' >>> 'element of index 1 is {0[1]}'.format([20, 10, 5])'element of index 1 is 10' >>> 'My name is {person[name]}'.format(person = {'name' : 'Justin', 'age' : 35}) 'My name is Justin' >>> |
當然,舊式的格式指定,在新的格式化方法中也可以支援。例如:
| >>> '{0:d} {1:.2f} {2:s}'.format(1, 99.3, 'Justin') '1 99.30 Justin' >>> 'example:{0:.2f}'.format(19.234)'example:19.23' >>> 'example:{0:6.2f}'.format(19.234)'example: 19.23' |
在預留空白時,可以使用>指定靠右對齊,使用<指定靠左對齊。例如:
| >>> 'example:{0:>10.2f}!!'.format(19.234)'example: 19.23!!' >>> 'example:{0:<10.2f}!!'.format(19.234)'example:19.23 !!' >>> |
如果只是要格式化單一數值,則可以使用format()函式。例如:
| >>> import math >>> format(math.pi, '.2f')'3.14' >>> |
更多字串格式化的介紹,可以參考 String Formatting。
沒有留言:
張貼留言