str.format()方法

在Python 2.6中引入的。str.format()是对%-formatting的改进。它使用正常的函数调用语法,并且可以通过对要转换为字符串的对象的__format __()方法进行扩展。

比如下面的例子:

1
2
name = "Tom"
print("Hello, {0}.".format(name))  #输出Hello, Tom.

“Hello, {0}.“为我们的模板。{0}为格式符,表示匹配format方法的第一项。变量name的值Tom为替换{0}的真实值。{0}代表了格式化操作。

整个”Hello, {0}.“.format(name)实际上构成一个字符串表达式。我们可以像一个正常的字符串那样,将它赋值给某个变量。比如:

1
2
3
name = "Tom"
str = "Hello, {0}.".format(name)
print(str)  #输出Hello, Tom.

使用str.format(),替换字段用大括号标记:

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
{ [field_name] [! conversion] [: format_spec] }  

field_name        ::=  arg_name ("." attribute_name | "[" element_index "]")*  
arg_name          ::=  [identifier | digit+]  
attribute_name    ::=  identifier  
element_index     ::=  digit+ | index_string  
index_string      ::=  <any source character except "]  "> +  
conversion        ::=  "r" | "s" | "a"

field_name指定要格式化的对象field_name本身以arg_name开头arg_name是数字或关键字 如果它是一个数字,它引用一个位置参数,如果它是一个关键字,它引用一个命名关键字参数。 如果格式字符串中的数字arg_names是序列0,1,2...,它们都可以省略,数字0,1,2...将按顺序自动插入。 arg_name后面可以跟任意数量的索引或属性表达式 .name”形式的表达式使用getattr()选择命名属性,而“[index]”形式的表达式使用__getitem __()执行索引查找。

例如:

1
2
3
4
5
6
"First, thou shalt count to {0}"  # 引用第一个位置参数
"Bring me a {}"                   # 隐式引用第一个位置参数
"From {} to {}"                   # 相当于"From {0} to {1}"
"My quest is {name}"              # 引用关键字参数'name'
"Weight in tons {0.weight}"       # 第一个位置参数的'weight'属性
"Units destroyed: {players[0]}"   # 关键字参数'players'的第一个元素。

示例

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
name = "Tom"
age = 56
str = "Hello, {}. You are {}.".format(name, age)
print(str) #输出Hello, Tom. You are 56.

#通过参数位置访问
str2 = "Hello, {1}. You are {0}.".format(age, name)
print(str2) #输出Hello, Tom. You are 56.

#通过参数名访问
str3 = "Hello, {name}. You are {age}.".format(age=66, name="Hank")
print(str3) #输出Hello, Hank. You are 66.

#通过参数的属性访问
c = 3-5j
str4 ="The complex number {0} is formed from the real part {0.real} and the imaginary part {0.imag}.)".format(c)
print(str4) #输出The complex number (3-5j) is formed from the real part 3.0 and the imaginary part -5.0.)

#通过参数的数据项访问 元组
coord = (3, 5)
str5 = 'X: {0[0]};  Y: {0[1]}'.format(coord)
print(str5) #输出X: 3;  Y: 5

执行以上程序会输出如下结果:

1
2
3
4
5
Hello, Tom. You are 56.
Hello, Tom. You are 56.
Hello, Hank. You are 66.
The complex number (3-5j) is formed from the real part 3.0 and the imaginary part -5.0.)
X: 3;  Y: 5

conversion指定在格式化之前的类型强制。通常,格式化的工作是由值本身的format()方法完成的。但是,在某些情况下,需要强制将类型格式化为字符串,从而覆盖其自己的格式化定义。通过在调用format()之前将值转换为字符串,可以绕过正常的格式化逻辑。当前支持三个转换标志:“!s’调用str(),’!r’调用repr()和’!a’一个调用ascii()。

例如:

1
2
3
4
5
s = "I am Tom."
print(str(s))  #输出I am Tom. (没有引号)
print(repr(s)) #输出'I am Tom.'. (有引号)
test = "repr() shows quotes: {!r}; str() doesn't: {!s}".format(s, s)
print(test)  #输出repr() shows quotes: 'I am Tom.'; str() doesn't: I am Tom.

执行以上程序会输出如下结果:

1
2
3
I am Tom.
'I am Tom.'
repr() shows quotes: 'I am Tom.'; str() doesn't: I am Tom.

format_spec语法

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
{[[fill]align][sign][#][0][width][,][.precision][type]}  
fill  可选,可以是任何字符  
align 可选,是对齐方式,可供选择的值有:  
     '<' 左对齐  
     '>' 右对齐  
     '=' 只对数字类型有效  
     '^'居中对齐
sign  可选,是对齐方式,可供选择的值有:
     '+' 表示正负数字都应使用符号。正数前加正号,负数前加负号;
     '-' 表示符号只能用于负数(这是默认行为)。正数前无符号,负数前加负号;
     ' ' 正数前加空格,负数前加负号;
#    可选,用于转换。 对于不同类型,替代形式的定义不同。 此选项仅对integer,float,complex和Decimal类型有效。 对于整数,当使用二进制,八进制或十六进制输出时,此选项将前缀“0b”,“0o”或“0x”添加到输出值。 对于浮点数,复数和十进制,备用形式会导致转换结果始终包含小数点字符,即使后面没有数字也是如此。 通常,只有在跟随数字的情况下,这些转换的结果中才会出现小数点字符。 此外,对于“g”和“G”转换,不会从结果中删除尾随零。
width    可选,数字宽度,表示总共输出多少位数字
.precision    可选,小数点后保留的位数,进行四舍五入计算。
typecode     可选
  s : 获取传入对象的__str__方法的返回值,并将其格式化到指定位置
  r : 获取传入对象的__repr__方法的返回值,并将其格式化到指定位置
  c : 如果是整数的话,将数字转换成其unicode对应的值10进制范围为0 <= i <= 1114111(py27则只支持0-255);如果是字符的话,将字符添加到指定位置
  o : 将整数转换成八进制表示,并将其格式化到指定位置
  x : 将整数转换成十六进制表示,并将其格式化到指定位置
  d : 将整数、浮点数转换成十进制表示,并将其格式化到指定位置
  e : 将整数、浮点数转换成科学计数法,并将其格式化到指定位置(小写e
  E : 将整数、浮点数转换成科学计数法,并将其格式化到指定位置(大写E
  f :  将整数、浮点数转换成浮点数表示,并将其格式化到指定位置(默认保留小数点后6位)
  F : 同上
  g : 自动调整将整数、浮点数转换成浮点型或科学计数法表示(超过6位数用科学计数法),并将其格式化到指定位置(如果是科学计数则是e;)
  G : 自动调整将整数、浮点数转换成浮点型或科学计数法表示(超过6位数用科学计数法),并将其格式化到指定位置(如果是科学计数则是E;)
  % : 百分比。将数字乘以100,并以固定格式(“f”)显示,后跟百分号。

示例 {[[fill]align]}

1
2
3
4
5
6
7
8
>>>'{:<30}'.format('left aligned')   #左对齐
'left aligned                  '
>>> '{:>30}'.format('right aligned') #右对齐
'                 right aligned'
>>> '{:^30}'.format('centered')      #居中对齐
'           centered           '
>>> '{:*^30}'.format('centered')     #居中对齐,不足的部分用*填充
'***********centered***********'

示例 {[fill][sign][type]}

1
2
3
4
5
6
7
8
>>> '{:+f}; {:+f}'.format(3.14, -3.14)  # + 表示正负数字都应使用符号。正数前加正号,负数前加负号;
'+3.140000; -3.140000'
>>> '{: f}; {: f}'.format(3.14, -3.14)  # 空格 表示正数前加空格,负数前加负号;
' 3.140000; -3.140000'
>>> '{:-f}; {:-f}'.format(3.14, -3.14)  # - 表示符号只能用于负数(这是默认行为)。正数前无符号,负数前加负号;等同于'{:f}; {:f}'
'3.140000; -3.140000'
>>> '{:f}; {:f}'.format(3.14, -3.14)
'3.140000; -3.140000'

示例 {:[type]}

1
2
3
4
5
>>> "int: {0:d};  hex: {0:x};  oct: {0:o};  bin: {0:b}".format(42)
'int: 42;  hex: 2a;  oct: 52;  bin: 101010'
>>> # with 0x, 0o, or 0b as prefix:
>>> "int: {0:d};  hex: {0:#x};  oct: {0:#o};  bin: {0:#b}".format(42)
'int: 42;  hex: 0x2a;  oct: 0o52;  bin: 0b101010'

示例 {:,}

1
2
>>> '{:,}'.format(1234567890)
'1,234,567,890'

示例 {:[type]%}

1
2
3
4
>>> points = 19
>>> total = 22
>>> 'Correct answers: {:.2%}'.format(points/total)
'Correct answers: 86.36%'

示例 两种方式引用字典的元素

1
2
3
4
5
person = {'name': 'Eric', 'age': 74}
a = "Hello, {name}. You are {age}.".format(name=person['name'], age=person['age'])
b ="Hello, {name}. You are {age}.".format(**person)
print(a) # 输出Hello, Eric. You are 74.
print(b) # 输出Hello, Eric. You are 74.

为什么str.format()并不好
使用str.format()的代码比使用%-formatting的代码更易读,但当处理多个参数和更长的字符串时,str.format()仍然可能非常冗长。

1
2
3
4
5
6
7
8
9
first_name = "Eric"
last_name = "Idle"
age = 74
profession = "comedian"
affiliation = "Monty Python"
print(("Hello, {first_name} {last_name}. You are {age}. " +
       "You are a {profession}. You were a member of {affiliation}.") \
       .format(first_name=first_name, last_name=last_name, age=age, \
               profession=profession, affiliation=affiliation))

执行以上程序会输出如下结果:

1
Hello, Eric Idle. You are 74. You are a comedian. You were a member of Monty Python.

如果你有想要传递给字典中的.format()的变量,那么你可以用.format(** some_dict)解压缩它,并通过字符串中的键引用这些值,但是必须有更好的的方法。


转载请注明本网址。