3/20python之格式化字符串

作者: 王悟冥 | 来源:发表于2019-02-21 00:22 被阅读13次
格式化字符串,就是将字符串以特定格式输出。

Python2.6 开始,新增了一种格式化字符串的函数 【str.format()】,它增强了字符串格式化的功能。

format函数可以接受不限个参数,位置可以不按顺序。
例如:

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

不设置指定位置,按默认顺序

   >>> "{1}{2}{0}".format("H","S","5")#设置指定位置
   'S5H'

指定的位置,也是以自然数排列的,从0位开始数。

   >>> "{1}  {0}  {1}".format("he", "llo")  
   'llo he llo'

设置指定位置。包含空格,在{}之间留有空格,所以输出时也会包含空格。

下面是【str.format()】格式化数字的多种方法:


str.format()格式化数字的多种方法:
   >>> print("{:.2f}".format(3.1415926));
   3.14

【{:.2f}】输出保留小数点后两位

数字输入错误实例
   >>>print("{:+.2f}".format(3.14159265));
   +3.14
   >>>print("{:+.2f}".format(-1));
   -1.00

带符号保留小数点后两位

   >>>print("{:.0f}".format(2.71828));
   3

不带小数

   >>>print("{:0>2d}".format(5));
   05

数字补0(填充左边,宽度为2)

   >>>print("{:x<4d}".format(5));
   5xxx
   >>>print("{:x<4d}".format(5));
   10xxx

数字补x(填充右边,宽度为4)

   >>>print("{:,}".format(100404500));
   100,404,500

**以逗号分隔的数字格式

   >>>print("{:.2%}".format(0.12));
   12.00%

百分比格式

   >>>print("{:.2e}".format(100000000));
   1.00e+08

**指数记法

   >>>print("{:10d}".format(13));
           13#13的前面都是空格,13在宽度为10的最右边。

右对齐(默认,宽度为10)

   >>>print("{:<10d}".format(13));
   13        #13的后面都是空格,13在宽度为10的最左边。

左对齐(宽度为10)

   >>>print("{:^10d}".format(13));
       13    #13位于宽度为10的中间。

中间对齐(宽度为10)

   >>>a = print('{:b}'.format(11));
   >>>b = print('{:d}'.format(11));
   >>>c = print('{:o}'.format(11));
   >>>d = print('{:x}'.format(11));
   >>>e = print('{:#x}'.format(11));
   >>>f = print('{:#X}'.format(11));
   >>>a
   1011
   >>>b
   11
   >>>c
   13
   >>>d
   b
   >>>e
   0xb
   >>>f
   0XB

各个进制

【b】、【d】、【o】、【x】分别是二进制、十进制、八进制、十六进制。
【+】表示在正数前显示+,负数前显示-;(空格)表示在正数前加空格
【^】,【<】,【>】分别是居中,左对齐,右对齐,后面带宽度,【:】号后面带填充的字符,只能是一个字符,不指定则默认是用空格填充。

str.format()函数说明

相关文章

网友评论

    本文标题:3/20python之格式化字符串

    本文链接:https://www.haomeiwen.com/subject/rbihyqtx.html