The Python 2.6 introduced str.format()
function seems to be somewhat different from how %
is used. What is the best way to use it in what situation?
The examples below are examples of each method, both of which show the same results. What's the difference?
#!/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 # "i am a python string!"
print b # "i am a python string!"
print c # "with an arg!"
print d # "with an arg!"
Also, when will the string formatting work take place on Python? For example, if the logging level is set to HIGH, does the %
below affect performance? If so, is there a way to avoid him?
log.debug("some debug info: %s" % some_info)
First of all, to answer the first question, .format
looks more sophisticated in many ways. %
can be a little annoying in the way you accept variables or tuples. The example below always looks like it will work
"hi there %s" % name
If the name
variable is (1, 2, 3)
, it will cause TypeError
. If the above example is to always work,
"hi there %s" % (name,)
You need to write code in a rather messy way, as shown in . On the other hand, .format
does not have this problem. Also, in the case of the example you uploaded, .format
will look much cleaner.
If you don't use this method, it's probably one of the following two cases.
To answer the second question, the string formatting task is performed simultaneously when performing other operations. Python then performs operations before calling a function. Therefore, in the example of log.debug
you uploaded, "some debug info: %s"%some_info
is performed first, and then converted to a function such as "some debug info:roflcopters are active"
.
© 2024 OneMinuteCode. All rights reserved.