python字符串格式化 % vs format优缺点与区别【面试题详解】

今天爱分享给大家带来python字符串格式化 % vs format优缺点与区别【面试题详解】,希望能够帮助到大家。

Python2.6中引入string.format()方法,语法和原先%澡作符的字符串格式化差异较大

在什么情况下使用哪种更好?

以下的输出是一致的,有什么区别


#!/usr/bin/python
sub1 = "python string!"
sub2 = "an arg"

a = "i am a %s"%sub1
b = "i am a {0}".format(sub1)

c = "with %(kwarg)s!"%{'kwarg':sub2}
d = "with {kwarg}!".format(kwarg=sub2)

print a
print b
print c
print d


.format 看起来更加强大,可以用在很多情况.

例如你可以在格式化时重用传入的参数,而你用%时无法做到这点

另一个比较讨厌的是,%只处理 一个变量或一个元组, 你或许会认为下面的语法是正确的


"hi there %s" % name


但当name恰好是(1,2,3)时,会抛出TypeError异常.为了保证总是正确的,你必须这么写


"hi there %s" % (name,)   # supply the single argument as a single-item tuple


这么写很丑陋, .format没有这些问题

什么时候不考虑使用.format



你对.format知之甚少
使用Python2.5

原文链接:https://blog.itblood.com/3908.html,转载请注明出处。
0
我和朋友陪妈妈去露营 (Camp With Mom Extend)官方中文版 [PC+安卓] [1.5G] [SLG/中文/动态]
我和朋友陪妈妈去露营 (Camp With Mom Extend)官方中文版 [PC+安卓] [1.5G] [SLG/中文/动态]
刚刚 有人购买 去瞅瞅看

站点公告

显示验证码
没有账号?注册  忘记密码?