美文网首页
2018-05-15 python的str.format

2018-05-15 python的str.format

作者: lucasdada | 来源:发表于2018-05-15 10:19 被阅读0次

format方法被用于字符串的格式化输出。

 print('{0}+{1}={2}'.format(1,2,1+2))   #in
1+2=3   #out

可见字符串中大括号内的数字分别对应着format的几个参数。

若省略数字:

print('{}+{}={}'.format(1,2,1+2))   #in

可以得到同样的输出结果。但是替换顺序默认按照[0],[1],[2]...进行。

若替换{0}和{1}:

print('{1}+{0}={2}'.format(1,2,1+2))   #in

2+1=3   #out

输出字符串:

print('{0} am {1}'.format('i','alex'))  
i am alex   #out

输出参数的值:

1 length = 4
2 name = 'alex'
3 print('the length of {0} is {1}'.format(name,length))
the length of alex is 4

精度控制:

print('{0:.3}'.format(1/3))
0.333

宽度控制:

print('{0:7}{1:7}'.format('use','python'))
use    python 

精宽度控制(宽度内居左):

print('{0:<7.3}..'.format(1/3))   
0.333  ..

其实精宽度控制很类似于C中的printf函数。

同理'>'为居右,'^'为居中。符号很形象。

相关文章

  • 2018-05-15 python的str.format

    format方法被用于字符串的格式化输出。 可见字符串中大括号内的数字分别对应着format的几个参数。 若省略数...

  • Python 标准化输出

    一、 str.format() Python2.6 开始,新增了一种格式化字符串的函数 str.format()...

  • js实用函数集;

    Menu str.format() str.format()

  • 013.Python格式化

    Python格式化 1. 概述 Python2.6 开始,新增了一种格式化字符串的函数 str.format(),...

  • Java字符串format插值代码

    用过python str.format的肯定觉得java的String.format弱到爆了,几乎和c的print...

  • python 常用的format()函数

    基本语法 format()函数作为python的内置函数,用于格式化字符串str.format(),有了此函数可以...

  • 字符串的格式化操作

    旧式字符串格式化%运算符,位置格式化(python2) str.format字符串格式化(python3,它存在一...

  • format函数

    自python2.6开始,新增了一种格式化字符串的函数str.format(),可谓威力十足。那么,他跟之前的%型...

  • python_format (处理字符串)函数

    自python2.6开始,新增了一种格式化字符串的函数str.format(),可谓威力十足。那么,他跟之前的%型...

  • python之format函数

    自python2.6开始,新增了一种格式化字符串的函数str.format(),可谓威力十足。那么,他跟之前的%型...

网友评论

      本文标题:2018-05-15 python的str.format

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