零基础学Python注意事项(五)——解读format()函数

format()是一种格式化的函数,有如下表现形式:

1.位置参数:若不指定位置则默认从左侧开始(序号为0)

>>> "{0} {1} {2}".format('I','love','you')
'I love you'
>>> "{2} {1} {0}".format('I','love','you')
'you love I'

2.关键字参数:

>>> '{a} love {b} {c}'.format (a='I',b='you',c='too')
'I love you too'
>>> '{b} love {c} {a}'.format (a='I',b='you',c='too')
'you love too I'

3.通过列表填充:

list=['world','python']
>>> print('hello {names[0]}  i am {names[1]}'.format(names=list))
hello world  i am python
>>> print('hello {0[0]}  i am {0[1]}'.format(list))
hello world  i am python

4.通过字典填充:

>>> dict={'obj':'world','name':'python'}
>>> print('hello {names[obj]} i am {names[name]}'.format(names=dict))
hello world i am python

5.通过类的属性填充:(可能运行不了)

>>> class Person(object):
	def __init__(self,name, age):
		self.name = name
		self.age = age
print('name is {p.name}, age is {p.age}'.format(p = Person('lili', 12)))

6.小数位保留:(自动四舍五入)

>>> '{:.2f}'.format(3.1415926)
'3.14'

当只有一个元素的时候,可以省略冒号前的0,冒号表示格式化符号的开始。

>>> '{0:.2f} {1}'.format(3.1415926,555)
'3.14 555'

7. 使用","作用千位分隔符;

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

8.  百分数显示:

>>> points = 4
>>> total=10
>>> 'Correct answers: {:.2%}'.format(points/total)
'Correct answers: 40.00%'
>>> 'Correct answers: {:%}'.format(points/total)
'Correct answers: 40.000000%'
>>> 'Correct answers: {:}'.format(points/total)
'Correct answers: 0.4'

9.如果是双层大括号结构,则认为第二层大括号为普通字符串,不会进行格式化。例如:

print ("{} 对应的位置是 {{普通字符串}}".format("字符串"))

输出为:字符串 对应的位置是 {普通字符串},注意加粗部分,第二层大括号会作为普通的字符串,不会进行格式化。

>>> '{{0}}'.format (555)
'{0}'

 

发布了32 篇原创文章 · 获赞 17 · 访问量 4924

猜你喜欢

转载自blog.csdn.net/mango_ZZY/article/details/97613725
今日推荐