http://kuanghy.github.io/2016/11/25/python-str-format

http://blog.csdn.net/i_chaoren/article/details/77922939

 转载,

Python 在 2.6 版本中新加了一个字符串格式化方法: str.format()。它的基本语法是通过 {} 和 : 来代替以前的 %.。格式化时的占位符语法:

replacement_field ::= "{" [field_name] ["!" conversion] [":" format_spec] "}"

“映射”规则

通过位置

str.format() 可以接受不限个参数,位置可以不按顺序:

>>> "{0} {1}".format("hello", "world")'hello world'>>> "{} {}".format("hello", "world")'hello world'>>> "{1} {0} {1}".format("hello", "world")'world hello world'

通过关键字参数

使用关键参数时字符串中需要提供参数名:

>>> "I am {name}, age is {age}".format(name="huoty", age=18)'I am huoty, age is 18'>>> user = {"name": "huoty", "age": 18}>>> "I am {name}, age is {age}".format(**user)'I am huoty, age is 18'

通过对象属性

str.format() 可以直接读取用户属性:

>>> class User(object):...     def __init__(self, name, age):...         self.name = name...         self.age = age...         ...     def __str__(self):...         return "{self.name}({self.age})".format(self=self)...     ...     def __repr__(self):...         return self.__str__()...     ...>>> user = User("huoty", 18)>>> userhuoty(18)>>> "I am {user.name}, age is {user.age}".format(user=user)'I am huoty, age is 18'

通过下标

在需要格式化的字符串内部可以通过下标来访问元素:

>>> names, ages = ["huoty", "esenich", "anan"], [18, 16, 8]>>> "I am {0[0]}, age is {1[2]}".format(names, ages)'I am huoty, age is 8'>>> users = {"names": ["huoty", "esenich", "anan"], "ages": [18, 16, 8]}>>> "I am {names[0]}, age is {ages[0]}".format(**users)

指定转化

可以指定字符串的转化类型:

 conversion ::= "r" | "s" | "a"

其中 “!r” 对应 repr(); “!s” 对应 str(); “!a” 对应 ascii()。 示例:

>>> "repr() shows quotes: {!r}; str() doesn't: {!s}".format('test1', 'test2')"repr() shows quotes: 'test1'; str() doesn't: test2"

格式限定符

填充与对齐

填充常跟对齐一起使用。^, <, > 分别是居中、左对齐、右对齐,后面带宽度, : 号后面带填充的字符,只能是一个字符,不指定则默认是用空格填充。

>>> "{:>8}".format("181716")'  181716'>>> "{:0>8}".format("181716")'00181716'>>> "{:->8}".format("181716")'--181716'>>> "{:-<8}".format("181716")'181716--'>>> "{:-^8}".format("181716")'-181716-'>>> "{:-<25}>".format("Here ")'Here -------------------->'

浮点精度

用 f 表示浮点类型,并可以在其前边加上精度控制:

>>> "[ {:.2f} ]".format(321.33345)'[ 321.33 ]'>>> "[ {:.1f} ]".format(321.33345)'[ 321.3 ]'>>> "[ {:.4f} ]".format(321.33345)'[ 321.3335 ]'>>> "[ {:.4f} ]".format(321)'[ 321.0000 ]'

还可以为浮点数指定符号,+ 表示在正数前显示 +,负数前显示 -; (空格)表示在正数前加空格,在幅负数前加 -;- 与什么都不加({:f})时一致:

>>> '{:+f}; {:+f}'.format(3.141592657, -3.141592657)'+3.141593; -3.141593'>>> '{: f}; {: f}'.format(3.141592657, -3.141592657)' 3.141593; -3.141593'>>> '{:f}; {:f}'.format(3.141592657, -3.141592657)'3.141593; -3.141593'>>> '{:-f}; {:-f}'.format(3.141592657, -3.141592657)'3.141593; -3.141593'>>> '{:+.4f}; {:+.4f}'.format(3.141592657, -3.141592657)'+3.1416; -3.1416'

指定进制

>>> "int: {0:d};  hex: {0:x};  oct: {0:o};  bin: {0:b}".format(18)'int: 18;  hex: 12;  oct: 22;  bin: 10010'>>> "int: {0:d};  hex: {0:#x};  oct: {0:#o};  bin: {0:#b}".format(18)'int: 18;  hex: 0x12;  oct: 0o22;  bin: 0b10010'

千位分隔符

可以使用 “,” 来作为千位分隔符:

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

百分数显示

>>> "progress: {:.2%}".format(19.88/22)'progress: 90.36%'

事实上,format 还支持更多的类型符号:

type ::= "b" | "c" | "d" | "e" | "E" | "f" | "F" | "g" | "G" | "n" | "o" | "s" | "x" | "X" | "%"

其他技巧

占位符嵌套

某些时候占位符嵌套还是很有用的:

>>> '{0:{fill}{align}16}'.format("hello", fill='*', align='^')'*****hello******'>>>>>> for num in range(5,12):...     for base in "dXob":...         print("{0:{width}{base}}".format(num, base=base, width=5), 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

作为函数使用

可以先不指定格式化参数,而是在不要的地方作为函数来调用:

>>> email_f = "Your email address was {email}".format>>> print(email_f(email="suodhuoty@gmail.com"))Your email address was sudohuoty@gmail.com

转义大括号

当在字符串中需要使用大括号时可以用大括号转义:

>>> " The {} set is often represented as `0` ".format("empty")' The empty set is often represented as {0} '

You need to double the{{ and }}:

>>> x = " {{ Hello }} {0} "
>>> print x.format(42)' { Hello } 42 '


格式控制信息

   format()方法中<模板字符串>的槽除了包括参数序号,还可以包括格式控制信息。此时,槽的内部样式如下:

     {<参数序号>: <格式控制标记>}

     其中,<格式控制标记>用来控制参数显示时的格式,包括:<填充><对齐><宽度>,<.精度><类型>6 个字段,这些字段都是可选的,可以组合使用,逐一介绍如下。

python 字符串format()技能总结_python

<宽度>

指当前槽的设定输出字符宽度,如果该槽对应的format()参数长度比<宽度>设定值大,则使用参数实际长度。如果该值的实际位数小于指定宽度,则位数将被默认以空格字符补充。

<对齐>

指参数在<宽度>内输出时的对齐方式,分别使用<、>和^三个符号表示左对齐、右对齐和居中对齐。

<填充>

指<宽度>内除了参数外的字符采用什么方式表示,默认采用空格,可以通过<填充>更换。

[python] view plain copy

  1. s = "PYTHON"  

  2.   

  3. "{0:30}".format(s)  

  4. Out[17]: 'PYTHON                        '  

  5.   

  6. "{0:>30}".format(s)  

  7. Out[18]: '                        PYTHON'  

  8.   

  9. "{0:*^30}".format(s)  

  10. Out[19]: '************PYTHON************'  

  11.   

  12. "{0:-^30}".format(s)  

  13. Out[20]: '------------PYTHON------------'  

  14.   

  15. "{0:3}".format(s)  

  16. Out[21]: 'PYTHON'  

逗号(,)

<格式控制标记>中逗号(,)用于显示数字的千位分隔符,例如:

[python] view plain copy

  1. "{0:-^20,}".format(1234567890)  

  2. Out[24]: '---1,234,567,890----'  

  3.   

  4. "{0:-^20}".format(1234567890#对比输出  

  5. Out[25]: '-----1234567890-----'  

  6.   

  7. "{0:-^20,}".format(12345.67890)  

  8. Out[26]: '----12,345.6789-----'  

 <.精度>

表示两个含义,由小数点(.)开头。对于浮点数,精度表示小数部分输出的有效位数。对于字符串,精度表示输出的最大长度。

[python] view plain copy

  1. "{0:.2f}".format(12345.67890)  

  2. Out[29]: '12345.68'  

  3.   

  4. "{0:H^20.3f}".format(12345.67890)  

  5. Out[30]: 'HHHHH12345.679HHHHHH'  

  6.   

  7. "{0:.4}".format("PYTHON")  

  8. Out[31]: 'PYTH'  

 <类型>

表示输出整数和浮点数类型的格式规则。对于整数类型,输出格式包括6 种:

  • b: 输出整数的二进制方式;

  • c: 输出整数对应的 Unicode 字符;

  • d: 输出整数的十进制方式;

  • o: 输出整数的八进制方式;

  • x: 输出整数的小写十六进制方式;

  • X: 输出整数的大写十六进制方式;

[python] view plain copy

  1. "{0:b},{0:c},{0:d},{0:o},{0:x},{0:X}".format(425)  

  2. Out[32]: '110101001,,425,651,1a9,1A9'  

对于浮点数类型,输出格式包括4 种:

  • e: 输出浮点数对应的小写字母 e 的指数形式;

  • E: 输出浮点数对应的大写字母 E 的指数形式;

  • f: 输出浮点数的标准浮点形式;

  • %: 输出浮点数的百分形式。

     浮点数输出时尽量使用<.精度>表示小数部分的宽度,有助于更好控制输出格式。

[python] view plain copy

  1. "{0:e},{0:E},{0:f},{0:%}".format(3.14)  

  2. Out[33]: '3.140000e+00,3.140000E+00,3.140000,314.000000%'  

  3.   

  4. "{0:.2e},{0:.2E},{0:.2f},{0:.2%}".format(3.14)  

  5. Out[34]: '3.14e+00,3.14E+00,3.14,314.00%'