python学习:format方法

来源:互联网 发布:手游刷枪软件 编辑:程序博客网 时间:2024/05/16 12:05

有时我们并不想用其他信息来构造字符串。这儿 format() 方法就很有用。

1 #!/usr/bin/python

2 # Filename: str_format.py

3 age = 254

 name = 'Swaroop

'5 print('{0} is {1} years old'.format(name, age))

6 print('Why is {0} playing with that python?'.format(name))

输出:1 $ python str_format.py

            2 Swaroop is 25 years old

            3 Why is Swaroop playing with that python?

运行原理:一个字符串能使用确定的格式,随后,可以调用 format 方法来代替这些格式,参数要与 format 方法的参数保持一致。

观察首次使用 0 的地方,这与 format 方法的第一个参变量 name 相一致。类似地,第二个格式 1 与 format 方法的第二个参变量 age 相一致。

注意,也可用字符串连接: name + ’ is ’ str(age) + ’ years old’ 来实现,但这似乎比较难看,容易出错。

第二,转为字符串的操作由 format 自动完成,而不需要明确的转换。

第三,用 format 方法的时候,不必处理用过的变量和 vice-versa 就能改变消息。

在 Python 中, format 方法就是用参变量的值代替格式符。更多细节如下:

1 >>> '{0:.3}'.format(1/3) # decimal (.) precision of 3 for float

2 '0.333'

3 >>> '{0:_^11}'.format('hello') # fill with underscores (_) with thetext

4 centered (^) to 11 width

5 '___hello___'

6 >>> '{name} wrote {book}'.format(name='Swaroop', book='A Byte ofPython')

7 # keyword-based

8 'Swaroop wrote A Byte of Python'

更多关于格式在 Python Enhancement Proposal No.3101 中有解释。

原创粉丝点击