Python2.6 開始,新增了一種格式化字符串的函數(shù) str.format(),它增強(qiáng)了字符串格式化的功能。 基本語(yǔ)法是通過 {} 和 : 來代替以前的 % 。 format 函數(shù)可以接受不限個(gè)參數(shù),位置可以不按順序。 實(shí)例>>>'{} {}'.format('hello', 'world') # 不設(shè)置指定位置,按默認(rèn)順序'hello world' >>> '{0} {1}'.format('hello', 'world') # 設(shè)置指定位置'hello world' >>> '{1} {0} {1}'.format('hello', 'world') # 設(shè)置指定位置'world hello world' 也可以設(shè)置參數(shù): 實(shí)例#!/usr/bin/python# -*- coding: UTF-8 -*- print('網(wǎng)站名:{name}, 地址 {url}'.format(name='菜鳥教程', url='www.runoob.com')) # 通過字典設(shè)置參數(shù)site = {'name': '菜鳥教程', 'url': 'www.runoob.com'}print('網(wǎng)站名:{name}, 地址 {url}'.format(**site)) # 通過列表索引設(shè)置參數(shù)my_list = ['菜鳥教程', 'www.runoob.com']print('網(wǎng)站名:{0[0]}, 地址 {0[1]}'.format(my_list)) # '0' 是必須的 輸出結(jié)果為: 網(wǎng)站名:菜鳥教程, 地址 www.runoob.com網(wǎng)站名:菜鳥教程, 地址 www.runoob.com網(wǎng)站名:菜鳥教程, 地址 www.runoob.com 也可以向 str.format() 傳入對(duì)象: 實(shí)例#!/usr/bin/python# -*- coding: UTF-8 -*- class AssignValue(object): def __init__(self, value): self.value = valuemy_value = AssignValue(6)print('value 為: {0.value}'.format(my_value)) # '0' 是可選的 輸出結(jié)果為: value 為: 6 數(shù)字格式化下表展示了 str.format() 格式化數(shù)字的多種方法: >>> print('{:.2f}'.format(3.1415926));3.14
^, , > 分別是居中、左對(duì)齊、右對(duì)齊,后面帶寬度, : 號(hào)后面帶填充的字符,只能是一個(gè)字符,不指定則默認(rèn)是用空格填充。 + 表示在正數(shù)前顯示 +,負(fù)數(shù)前顯示 -; (空格)表示在正數(shù)前加空格 b、d、o、x 分別是二進(jìn)制、十進(jìn)制、八進(jìn)制、十六進(jìn)制。 此外我們可以使用大括號(hào) {} 來轉(zhuǎn)義大括號(hào),如下實(shí)例: 實(shí)例#!/usr/bin/python# -*- coding: UTF-8 -*- print ('{} 對(duì)應(yīng)的位置是 {{0}}'.format('runoob')) 輸出結(jié)果為: runoob 對(duì)應(yīng)的位置是 {0} |
|