python开发之str.format()用法实例分析

本文实例分析了python开发之str.format()用法。分享给大家供大家参考,具体如下:

格式化一个字符串的输出结果,我们在很多地方都可以看到,如:c/c++中都有见过

下面看看python中的字符串格式函数str.format():

#使用str.format()函数
#使用'{}’占位符
print(‘i\’m {},{}’.format(‘hongten’,’welcome to my space!’))
print(‘#’ * 40)
#也可以使用'{0}’,'{1}’形式的占位符
print(‘{0},i\’m {1},my e-mail is {2}’.format(‘hello’,’hongten’,’hongtenzone@foxmail.com’))
#可以改变占位符的位置
print(‘{1},i\’m {0},my e-mail is {2}’.format(‘hongten’,’hello’,’hongtenzone@foxmail.com’))
print(‘#’ * 40)
#使用'{name}’形式的占位符
print(‘hi,{name},{message}’.format(name = ‘tom’,message = ‘how old are you?’))
print(‘#’ * 40)
#混合使用'{0}’,'{name}’形式
print(‘{0},i\’m {1},{message}’.format(‘hello’,’hongten’,message = ‘this is a test message!’))
print(‘#’ * 40)
#下面进行格式控制
import math
print(‘the value of pi is approximately {}.’.format(math.pi))
print(‘the value of pi is approximately {!r}.’.format(math.pi))
print(‘the value of pi is approximately {0:.3f}.’.format(math.pi))
table = {‘sjoerd’: 4127, ‘jack’: 4098, ‘dcab’: 7678}
for name, phone in table.items():
print(‘{0:10} ==> {1:10d}’.format(name, phone))
table = {‘sjoerd’: 4127, ‘jack’: 4098, ‘dcab’: 8637678}
print(‘jack: {0[jack]:d}; sjoerd: {0[sjoerd]:d}; ”dcab: {0[dcab]:d}’.format(table))

运行效果:

python 3.3.2 (v3.3.2:d047928ae3f6, may 16 2013, 00:03:43) [msc v.1600 32 bit (intel)] on win32
type “copyright”, “credits” or “license()” for more information.
>>> ================================ restart ================================
>>>
i’m hongten,welcome to my space!
########################################
hello,i’m hongten,my e-mail is hongtenzone@foxmail.com
hello,i’m hongten,my e-mail is hongtenzone@foxmail.com
########################################
hi,tom,how old are you?
########################################
hello,i’m hongten,this is a test message!
########################################
the value of pi is approximately 3.141592653589793.
the value of pi is approximately 3.141592653589793.
the value of pi is approximately 3.142.
jack ==> 4098
sjoerd ==> 4127
dcab ==> 7678
jack: 4098; sjoerd: 4127; dcab: 8637678
>>>

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

Posted in 未分类

发表评论