ITeye博客

string格式化输出

studypi · 2017-08-16 17:27 · python · 编程语言 · Markdown

一.按照一定格式输出,利用%s作,占位作用,传入参数是元组,参照例子。

>>> str="%s,%s!"
>>> val=("hello","world")
>>> print str%val
hello,world!

二.格式化浮点数:%.3,其中3是小数位,看例子比较明了。

>>> strf="%.3f three decimails"
>>> print strf%1.23456
1.235 three decimails
>>> strf="%.4f three decimails"
>>> print strf%1.23456
1.2346 three decimails

三.字符的重点格式化--宽度,浮点数精度,对齐,0填充 一般是这种格式%d.ds(其中d是具体的数字),“.”之前的是宽度为d “.”之后的数字一般是指浮点数有d位小数 %0ds用0填充,是指当s的长度小于d,就用0填充 导入pi

>>> from math import pi
>>> '%10f'%pi
'  3.141593'
>>> '%10.5f'%pi
'   3.14159'
>>> '%010.4f'%pi
'00003.1416'
>>> '%-10.4f'%pi
'3.1416    '
>>> '%+10.4f'%pi
'   +3.1416'
>>> '%10.4f'%pi
'    3.1416'
>>> '%-10.4f'%pi
'3.1416   

' 还有一个方法,带有*,*传入的值是数字

>>> '%.*s' %(4,"good day")
'good'
>>> '%.*s'%(2,"good day")
'go'

评论(0)

暂无评论。

评论功能维护中,当前仅展示历史评论。