Home > Backend Development > Python Tutorial > python格式化字符串实例总结

python格式化字符串实例总结

WBOY
Release: 2016-06-16 08:41:38
Original
1279 people have browsed it

本文实例总结了python格式化字符串的方法,分享给大家供大家参考。具体分析如下:

将python字符串格式化方法以例子的形式表述如下:

* 定义宽度
Python代码如下:

>>>'%*s' %(5,'some')
' some'
Copy after login

- 左对齐
Python代码如下:

>>>'%-*s' %(5,'some')
'some '
Copy after login

最小宽度为6的2位精度的浮点小数,位数不够时前补空格
Python代码如下:

>>>'%6.2f' %8.123
' 8.12'
Copy after login

字典形式,可在正数前显示加号,位数不够时前面补0
Python代码如下:

>>>'%(name)s = %(num)+06.2f' %{'name':'a','num':8.123}
'a = +08.12'
Copy after login

在八进制数前面显示零('0'),在十六进制前面显示'0x'或者'0X'(取决于用的是'x'还是'X')
Python代码如下:

>>>'dec: %d/oct: %#o/hex: %#X' % (123,123,123)
'dec: 123/oct: 0173/hex: 0X7B'
Copy after login

科学计数法
Python代码如下:

>>>'%e' % 1234.567890
'1.234568e+03'
Copy after login

希望本文所述对大家的Python程序设计有所帮助。

Related labels:
source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template