Python格式化操作符:%

來源:互聯網
上載者:User

標籤:attribute   encode   結果   delattr   int   center   語言   優先   複製   

原文田小計劃 原文出處:http://www.cnblogs.com/wilber2013/ (若轉載,請標明原文出處)

在編寫程式的過程中,經常需要進行格式化輸出,每次用每次查。乾脆就在這裡整理一下,以便索引。

格式化操作符(%)

"%"是Python風格的字串格式化操作符,非常類似C語言裡的printf()函數的字串格式化(C語言中也是使用%)。

下面整理了一下Python中字串格式化符合:

格式化符號

說明

%c

轉換成字元(ASCII 碼值,或者長度為一的字串)

%r

優先用repr()函數進行字串轉換

%s

優先用str()函數進行字串轉換

%d / %i

轉成有符號十進位數

%u

轉成無符號十進位數

%o

轉成無符號八位元

%x / %X

轉成無符號十六進位數(x / X 代錶轉換後的十六進位字元的大小寫)

%e / %E

轉成科學計數法(e / E控制輸出e / E)

%f / %F

轉成浮點數(小數部分自然截斷)

%g / %G

%e和%f / %E和%F 的簡寫

%%

輸出% (格式化字串裡麵包括百分比符號,那麼必須使用%%)

這裡列出的格式化符合都比較簡單,唯一想要強調一下的就是"%s"和"%r"的差別。

看個簡單的代碼:

string = "Hello\tWill\n"print "%s" %stringprint "%r" %string

代碼的輸出為:

其實,這裡的差異是str()和repr()兩個內建函數之間的差異:

  • str()得到的字串是面向使用者的,具有較好的可讀性
  • repr()得到的字串是面向機器的
    • 通常(不是所有)repr()得到的效果是:obj == eval(repr(obj))
格式化操作符輔助符

通過"%"可以進行字串格式化,但是"%"經常會結合下面的輔助符一起使用。

輔助符號

說明

*

定義寬度或者小數點精度

-

用做靠左對齊

+

在正數前面顯示加號(+)

#

在八位元前面顯示零(0),在十六進位前面顯示"0x"或者"0X"(取決於用的是"x"還是"X")

0

顯示的數字前面填充"0"而不是預設的空格

(var)

映射變數(通常用來處理欄位類型的參數)

m.n

m 是顯示的最小總寬度,n 是小數點後的位元(如果可用的話)

看一些簡單的 例子:

num = 100print "%d to hex is %x" %(num, num)print "%d to hex is %X" %(num, num)print "%d to hex is %#x" %(num, num)print "%d to hex is %#X" %(num, num) # 浮點數f = 3.1415926print "value of f is: %.4f" %f# 指定寬度和對齊students = [{"name":"Wilber", "age":27}, {"name":"Will", "age":28}, {"name":"June", "age":27}]print "name: %10s, age: %10d" %(students[0]["name"], students[0]["age"])print "name: %-10s, age: %-10d" %(students[1]["name"], students[1]["age"])print "name: %*s, age: %0*d" %(10, students[2]["name"], 10, students[2]["age"])# dict參數for student in students:print "%(name)s is %(age)d years old" %student

代碼輸出為:

對於Python的格式化操作符,不僅可以接受tuple類型的參數,也可以支援dict,象上面代碼的最後一部分,那麼格式化字串中就可以直接使用"%(key)s"(這裡的s根據具體類型改變)的方式表示dict中對應的value了。

字串模板

其實,在Python中進行字串的格式化,除了格式化操作符,還可以使用string模組中的字串模板(Template)對象。下面就主要看看Template對象的substitute()方法:

from string import Templates = Template("Hi, $name! $name is learning $language")print s.substitute(name="Wilber", language="Python")d = {"name": "Will", "language": "C#"}print s.substitute(d)# 用$$表示$符號s = Template("This book ($bname) is 17$$")print s.substitute(bname="TCP/IP")

代碼結果為:

字串內建函數format()

Python2.6開始,新增了一種格式化字串的函數str.format(),通過這個函數同樣可以對字串進行格式化處理。在format()函數中,使用“{}”符號來當作格式化操作符。

下面直接通過一些簡單的例子示範format()函數的基本使用:

# 位置參數print "{0} is {1} years old".format("Wilber", 28)print "{} is {} years old".format("Wilber", 28)print "Hi, {0}! {0} is {1} years old".format("Wilber", 28)# 關鍵字參數print "{name} is {age} years old".format(name = "Wilber", age = 28)# 下標參數li = ["Wilber", 28]print "{0[0]} is {0[1]} years old".format(li)# 填充與對齊# ^、<、>分別是置中、靠左對齊、靠右對齊,後面頻寬度# :號後面帶填充的字元,只能是一個字元,不指定的話預設是用空格填充print ‘{:>8}‘.format(‘3.14‘)print ‘{:<8}‘.format(‘3.14‘)print ‘{:^8}‘.format(‘3.14‘)print ‘{:0>8}‘.format(‘3.14‘)print ‘{:a>8}‘.format(‘3.14‘)# 浮點數精度print ‘{:.4f}‘.format(3.1415926)print ‘{:0>10.4f}‘.format(3.1415926)# 進位# b、d、o、x分別是二進位、十進位、八進位、十六進位print ‘{:b}‘.format(11)print ‘{:d}‘.format(11)print ‘{:o}‘.format(11)print ‘{:x}‘.format(11)print ‘{:#x}‘.format(11)print ‘{:#X}‘.format(11)# 千位分隔字元print ‘{:,}‘.format(15700000000)
str的內建函數

在最開始的時候,Python有一個專門的string模組,要使用string的方法要先import這個模組。從Python2.0開始, 為了方便使用,str類型添加了很多內建函數,這些函數可以實現跟string模組中函數相同的功能,也就是說,只要S是一個字串對象就可以直接使用內建函數,而不用import。

對於字串的格式化處理,也可以考慮使用str的其他內建函數:

>>> dir(str)[‘__add__‘, ‘__class__‘, ‘__contains__‘, ‘__delattr__‘, ‘__doc__‘, ‘__eq__‘, ‘__format__‘, ‘__ge__‘, ‘__getattribute__‘, ‘__getitem__‘, ‘__getnewargs__‘, ‘__getslice__‘, ‘__gt__‘, ‘__hash__‘, ‘__init__‘, ‘__le__‘, ‘__len__‘, ‘__lt__‘, ‘__mod__‘, ‘__mul__‘, ‘__ne__‘, ‘__new__‘, ‘__reduce__‘, ‘__reduce_ex__‘, ‘__repr__‘, ‘__rmod__‘, ‘__rmul__‘, ‘__setattr__‘, ‘__sizeof__‘, ‘__str__‘, ‘__subclasshook__‘, ‘_formatter_field_name_split‘, ‘_formatter_parser‘, ‘capitalize‘, ‘center‘, ‘count‘, ‘decode‘, ‘encode‘, ‘endswith‘, ‘expandtabs‘, ‘find‘, ‘format‘, ‘index‘, ‘isalnum‘, ‘isalpha‘, ‘isdigit‘, ‘islower‘, ‘isspace‘, ‘istitle‘, ‘isupper‘,‘join‘, ‘ljust‘, ‘lower‘, ‘lstrip‘, ‘partition‘, ‘replace‘, ‘rfind‘, ‘rindex‘, ‘rjust‘, ‘rpartition‘, ‘rsplit‘, ‘rstrip‘, ‘split‘, ‘splitlines‘, ‘startswith‘, ‘strip‘, ‘swapcase‘, ‘title‘, ‘translate‘, ‘upper‘, ‘zfill‘]

下面整理出來了一些常用的str類型的內建函數:

# 小寫 S.lower() # 大寫 S.upper() #大小寫互換 S.swapcase() # 首字母大寫 S.capitalize() # 輸出width個字元,S靠左對齊,不足部分用fillchar填充,預設的為空白格。 S.ljust(width,[fillchar]) # 靠右對齊 S.rjust(width,[fillchar]) # 中間對齊 S.center(width, [fillchar]) # 返回S中出現substr的第一個字母的標號,如果S中沒有substr則返回-1。start和end作用就相當於在S[start:end]中搜尋 S.find(substr, [start, [end]]) # 返回S中最後出現的substr的第一個字母的標號,如果S中沒有substr則返回-1,也就是說從右邊算起的第一次出現的substr的首字母標號 S.rfind(substr, [start, [end]]) # 計算substr在S中出現的次數 S.count(substr, [start, [end]]) #把S中的oldstar替換為newstr,count為替換次數S.replace(oldstr, newstr, [count]) # 把S中前後chars中有的字元全部去掉,可以理解為把S前後chars替換為None S.strip([chars]) S.lstrip([chars]) S.rstrip([chars]) # 以sep為分隔字元,把S分成一個list。maxsplit表示分割的次數。預設的分割符為空白字元 S.split([sep, [maxsplit]]) # 把seq代表的字串序列,用S串連起來 S.join(seq)
總結

本文整理了一些格式化字元,以及一些輔助指令,結合格式化操作符(%),就可以產生特定格式的字串了。也可以使用字串模板來進行字串格式化。

Python格式化操作符:%

相關文章

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.