1. 程式人生 > >python的字符串格式化

python的字符串格式化

defined from using eric 情況下 分時 -c 有效 define

1、python到底有那幾種字符串格式化模塊?

python有3種格式化字符串的方法:

  • 傳統的%字符串格式符
  • str.format函數
  • 字符串模版template

新的python 3.6+還提供了新的f修飾符

2、傳統的%字符串格式符

python采用了類似於在C語言中使用sprintf的字符串格式化輸出。String對象有一個獨特的內置操作:%操作符。 這也稱為字符串格式化或插值運算符。 給定格式%值(其中format是字符串),轉換規範將格式的%將替換為零個或多個元素值。

‘%[[(key)][flag][width][.precision]]type’%(key list)

如果format單個參數,則key可以是單個非元組對象: ‘%s’%key。否則,值必須是具有格式字符串指定的項目數的元組,或者是單個映射對象(例如,字典)。

flag可以是#, 0, -, 空格,或是+:

Flag    意義
#    The value conversion will use the ``alternate form‘‘ (where defined below).
0    The conversion will be zero padded for numeric values.
-    The converted value is left adjusted (overrides the "0" conversion if both are given).
     (a space) A blank should be left before a positive number (or empty 
string) produced by a signed conversion. + A sign character ("+" or "-") will precede the conversion (overrides a "space" flag).

type可以是下面定義不同類型:

type 意義                    註釋
d    Signed integer            decimal.    
i    Signed integer            decimal.    
o    Unsigned octal.             (
1) u Unsigned                decimal. x Unsigned hexadecimal (lowercase). (2) X Unsigned hexadecimal (uppercase). (2) e Floating point exponential format (lowercase). E Floating point exponential format (uppercase). f Floating point             decimal format. F Floating point             decimal format. g Same as "e" if exponent is greater than -4 or less than precision, "f" otherwise. G Same as "E" if exponent is greater than -4 or less than precision, "F" otherwise. c Single character (accepts integer or single character string). r String (converts any python object using repr()). (3) s String (converts any python object using str()). (4) % No argument is converted, results in a "%" character in the result.

比如:

  • >>> ‘%(name)s GPA is %(#)07.3f‘%{‘name‘:‘Yue‘, ‘#‘:88.2}
    ‘Yue GPA is 088.200‘

  • >>> ‘%(name)10s GPA is %(#) 7.2f‘%{‘name‘:‘Jun‘, ‘#‘:89.1299}
    ‘ Jun GPA is 89.13‘

3. str.format函數

PEP 3101 規定了使用str.format()函數格式化字符串的標準。str.format()的語法:

‘...{replacement_field}...‘.format(*arg, **kargs)

具體解釋如下:

replacement_field ::=  "{" [field_name] ["!" conversion] [":" format_spec] "}"
field_name        ::=  arg_name ("." attribute_name | "[" element_index "]")*
arg_name          ::=  [identifier | integer]
attribute_name    ::=  identifier
element_index     ::=  integer | index_string
index_string      ::=  <any source character except "]"> +
conversion        ::=  "r" | "s"
format_spec       ::=  <described in the next section>

例子:

>>> Bring {0} a {1}.format(me, apple)  # 和C#有點像,數字代表位置
Bring me a apple
>>> Bring {} a {}.format(me, apple) 
Bring me a apple
>>> Bring {name} a {fruit}.format(fruit=me, name=apple)
Bring apple a me

下面是format_spec的定義:

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

有時候,還需要更進一步定制,這時需要使用string模塊裏的formatter類來定制格式, Formatter類有以下公共函數:

  • format(format_string, *args, **kwargs):它調用下面vformat函數。
  • vformat(format_string, args, kwargs):根據參數和格式化串產生相應的字符串。它調用下面可以重載的函數。

此外,Formatter類還定義了其他一些可以重載的函數:

  • parse(format_string):分解格式化定義format_string;
  • get_field(field_name, args, kwargs):根據parse()的輸出,為某一field產生格式化對象;
  • get_value(key, args, kwargs):獲取某一field的值;
  • check_unused_args(used_args, args, kwargs)
  • format_field(value, format_spec)
  • convert_field(value, conversion)

4. 字符串模版template

模板支持基於$的替換,而不是正常的基於%的替換:

  • $$用於替換$。
  • $ identifier命名匹配映射關鍵字“identifier”的替換占位符。 默認情況下,“identifier”必須拼寫Python標識符。 $字符後面的第一個非標識符字符終止此占位符規範。
  • $ {identifier}相當於$ identifier。 當有效標識符字符跟隨占位符但不是占位符的一部分時,例如“$ {noun} ification”,則需要它。
  • 字符串中$在其他任何地方出現,都將導致ValueError異常。

例子:

>>> from string import Template
>>> s1 = Template(Today is $weekday, it is $weather)
>>> s1.substitute(weekday = Tuesday, weather = sunny)
Today is Tuesday, it is sunny
>>> s1.substitute(weekday = Tuesday)
...
KeyError: weather
>>> s1.safe_substitute(weekday = Tuesday)
Today is Tuesday, it is $weather
>>> s2 = Template($fruit is $2.99 per pound)
>>> s2.substitute(fruit = apple)
...
ValueError: Invalid placeholder in string: line 1, col 11
>>> s2 = Template($fruit is $$2.99 per pound)
>>> s2.substitute(fruit = apple)
apple is $2.99 per pound

References:

[1] https://docs.python.org/2/library/stdtypes.html#string-formatting

[2] https://docs.python.org/2/library/string.html

python的字符串格式化