编程中跟字符串打交道那是最常见的了,常用的有以下两种方法格式化字符串(%
or .format
)
方法一(%
)
# 格式的字符串与被格式化的字符串必须一一对应,需格式化的字符串多时,容易搞混
print 'hello %s, you sex is %s.' %('tab', 'boy')
# hello tab, you sex is boy.
print 'hello %s, you sex is %s.' %(boy', 'tab')
# hello boy, you sex is tab.
# 通过字典方式格式化,哪个字符将会格式化到哪里,清晰命了
print 'hello %(name)s, you sex is %(sex)s.' %{'name': 'tab', 'sex': 'boy'}
# hello tab, you sex is boy.
args = {'name': 'tab', 'sex': 'boy'}
print 'hello %(name)s, you sex is %(sex)s.' %(args)
# hello tab, you sex is boy.
方法二(.format
)
# 跟方法一第一种方式有点类似的格式化方式
print 'hello {0}, you sex is {1}.'.format('tab', 'boy')
# hello tab, you sex is boy.
# 注意:用字典方式格式化时,指定格式化字符时的位置可以调换
print 'hello {name}, you sex is {sex}.'.format(sex='boy', name='tab)
# hello tab, you sex is boy.
# '**'起到解包的作用
args = {'name': 'tab', 'sex': 'boy}
print 'hello {name}, you sex is {sex}.'.format(**args)
# hello tab, you sex is boy.
推荐使用 .format
方法进行格式化字符串,一来清晰明了,二来效率更高(format
是字符串 str 内置的方法)。更多关于 .format
的用法文档,用户可在交互模式下(终端输入 python
or ipython
or bpython
) 输入 help(str.format)
查看
安装 ipython (Ubuntu)
sudo pip install ipython