python的三种字符串格式化方法

1.最方便的

print 'hello %s and %s' % ('df', 'another df')

但是,有时候,我们有很多的参数要进行格式化,这个时候,一个一个一一对应就有点麻烦了,于是就有了第二种,字典形式的。上面那种是tuple形式的。

 

2.最好用的

print 'hello %(first)s and %(second)s' % {'first': 'df', 'second': 'another df'}

这种字典形式的字符串格式化方法,有一个最大的好处就是,字典这个东西可以和json文件相互转换,所以,当配置文件使用字符串设置的时候,就显得相当方便。

 //接口请求对返回的 response 进行判断       
if not(response.status_code == 200 and response.json()['success']): raise Exception('Fail to login. code: %s, message: %s' % (response.status_code, response.content))

3.最先进的

print 'hello {first} and {second}'.format(first='df', second='another df')

这种就像是写一个函数一样,有好处,就是可读性很好,但是笔者还是喜欢第二种。

原文地址:https://www.cnblogs.com/111testing/p/9615384.html