1. 程式人生 > >python之格式化字符串速記整理

python之格式化字符串速記整理

ssi nts form 表示 直接 ngs type ani 執行

一、格式化字符串的方式:

1、字符串表達式:

語法格式:‘%s’ % var 或 ‘%s %d’ % (var1, var2)

說明:%s、%d等為格式類型說明符

例子:

>>> this is a %s % (pear)
this is a pear
>>> there are %d %s and %d %s % (2, pear, 5, apple)
there are 2 pear and 5 apple

#使用字典格式 >>> there are %(count)d %(fruit)s
% {count:5, fruit:apples} there are 5 apples

2、字符串format方法:

語法格式:str.format()

說明:使用字符串的format方法

例子:

#使用相對位置參數
>>> astring = there are {} {} and {} {} >>> astring.format(2, pears, 5, apples)
there are 2 pears and 5 apples

#使用絕對位置參數 >>> astring = there are {0} {1} and {0} {2} >>> astring.format(2, pears, apples)
there are 2 pears and 2 apples

#使用關鍵字參數 >>> astring = ‘there are {count} {fruit1} and {count} {fruit2}‘
>>> astring.format(count=2, fruit1=‘pears‘, fruit2=‘apples‘)
‘there are 2 pears and 2 apples‘

3、format內建函數:

語法格式:format(value[, format_spec])

說明:第1個參數為字符串、數字等,第2個參數為格式說明符,省略格式說明符,就相當於str(value)

例子:

#缺省類型為s(字符串),可以省略不寫
>>> format(^表示居中,10表示寬度,不夠的位用#填充,#^10) ^表示居中,10表示寬度,不夠的位用#填充
>>> format(123,b) 1111011 >>> format(123,#b) 0b1111011 >>>

4、已格式化的字符串直接量(也就是一個帶格式的字符串,簡稱f-strings):

語法格式:f‘{expression[:format-spicifier]}‘

說明:類似於r‘string‘、b‘byte sequence‘的風格,f也可以是大寫的F,表達式expression可以是直接量、變量,對象屬性,函數調用、模塊方法執行等,還可以結合!s或!r對表示執行str或repr函數。格式化說明符可以省略。

例子:

>>> f{10:b}  
1010         
>>> f{10:x}  
a            
>>> f{12:x}  
c            
>>> f{12:X}  
C            
>>> f{12:#X} 
0XC
>>> f{12:02X}
0C
>>> f{12:2X} 
 C
>>> Fthis is a hex number {12:#2X} and an octet number {29:#o}
this is a hex number 0XC and an octet number 0o35
>>> import random
>>> Fthis is a hex number {random.randint(100,500):#2X} and an octet number {29:#o}
this is a hex number 0X8A and an octet number 0o35 
>>> import math
>>> print(fThe value of pi is approximately {math.pi:.3f}.)
The value of pi is approximately 3.142.
#表示式為變量,效果類似於shell字符串中變量替換,同時還可以在替換後進行格式化
>>> table = {Sjoerd: 4127, Jack: 4098, Dcab: 7678} >>> for name, phone in table.items(): ... print(f{name:10} ==> {phone:10d}) ... Sjoerd ==> 4127 Jack ==> 4098 Dcab ==> 7678
>>> animals = eels
>>> print(fMy hovercraft is full of {animals}.)
My hovercraft is full of eels.
>>> print(fMy hovercraft is full of {animals!r}.)
My hovercraft is full of eels.

5、字符串手動格式化

語法格式:str.rjust([width][, padding-char])、str.rjust([width][, padding-char])、center([width][, padding-char])、str.zfill()

說明:字符串的左、右、中對齊方法,第1個參數為寬度,第2個為字符串寬度小於指定寬度後填充的字符,缺省為空格。str.zfill()用於數字串填充0

例子:

>>> 12.zfill(5)
00012
>>> -3.14.zfill(7)
-003.14
>>> 3.14159265359.zfill(5)
3.14159265359
>>> this is a left indent string.ljust(40)
this is a left indent string            
>>> this is a left indent string.ljust(40,-)
this is a left indent string------------
>>>  

二、通用標準格式化說明符及特殊格式說明符如下:

format_spec     ::=  [[fill]align][sign][#][0][width][grouping_option][.precision][type]
fill            ::=  <any character>
align           ::=  "<" | ">" | "=" | "^"
sign            ::=  "+" | "-" | " "
width           ::=  digit+
grouping_option ::=  "_" | ","
precision ::= digit+ type ::= "b" | "c" | "d" | "e" | "E" | "f" | "F" | "g" | "G" | "n" | "o" | "s" | "x" | "X"

舊的字符串表達式格式:

>>> ‘%#x‘ % 255, ‘%x‘ % 255, ‘%X‘ % 255
(‘0xff‘, ‘ff‘, ‘FF‘)
>>> format(255, ‘#x‘), format(255, ‘x‘), format(255, ‘X‘)
(‘0xff‘, ‘ff‘, ‘FF‘)
>>> f‘{255:#x}‘, f‘{255:x}‘, f‘{255:X}‘
(‘0xff‘, ‘ff‘, ‘FF‘)

表示一個百分號%使用特殊類型符%:

>>> points = 19
>>> total = 22
>>> ‘Correct answers: {:.2%}‘.format(points/total)
‘Correct answers: 86.36%‘

使用時間專用格式:

>>> import datetime
>>> d = datetime.datetime(2010, 7, 4, 12, 15, 58)
>>> ‘{:%Y-%m-%d %H:%M:%S}‘.format(d)
‘2010-07-04 12:15:58‘

嵌套參數和更復雜例子:

>>> for align, text in zip(‘<^>‘, [‘left‘, ‘center‘, ‘right‘]):
...     ‘{0:{fill}{align}16}‘.format(text, fill=align, align=align)
...
‘left<<<<<<<<<<<<‘
‘^^^^^center^^^^^‘
‘>>>>>>>>>>>right‘
>>>
>>> octets = [192, 168, 0, 1]
>>> ‘{:02X}{:02X}{:02X}{:02X}‘.format(*octets)
‘C0A80001‘
>>> int(_, 16)
3232235521
>>>
>>> width = 5
>>> for num in range(5,12): 
...     for base in ‘dXob‘:
...         print(‘{0:{width}{base}}‘.format(num, base=base, width=width), end=‘ ‘)
...     print()
...
    5     5     5   101
    6     6     6   110
    7     7     7   111
    8     8    10  1000
    9     9    11  1001
   10     A    12  1010
   11     B    13  1011

更詳細的格式化說明可以參見python3.7.1參考手冊的章節:7.1. Fancier Output Formatting

python之格式化字符串速記整理