String concatenation vs. string formatting
Billy Mays
noway at nohow.com
Fri Jul 8 16:57:09 EDT 2011
On 07/08/2011 04:18 PM, Andrew Berg wrote:
> Is it bad practice to use this
>> logger.error(self.preset_file + ' could not be stored - ' +
>> sys.exc_info()[1])
> Instead of this?
>> logger.error('{file} could not be stored -
>> {error}'.format(file=self.preset_file, error=sys.exc_info()[1]))
>
>
> Other than the case where a variable isn't a string (format() converts
> variables to strings, automatically, right?) and when a variable is used
> a bunch of times, concatenation is fine, but somehow, it seems wrong.
> Sorry if this seems a bit silly, but I'm a novice when it comes to
> design. Plus, there's not really supposed to be "more than one way to do
> it" in Python.
If it means anything, I think concatenation is faster.
__TIMES__
a() - 0.09s
b() - 0.09s
c() - 54.80s
d() - 5.50s
Code is below:
def a(v):
out = ""
for i in xrange(1000000):
out += v
return len(out)
def b(v):
out = ""
for i in xrange(100000):
out += v+v+v+v+v+v+v+v+v+v
return len(out)
def c(v):
out = ""
for i in xrange(1000000):
out = "%s%s" % (out, v)
return len(out)
def d(v):
out = ""
for i in xrange(100000):
out = "%s%s%s%s%s%s%s%s%s%s%s" % (out,v,v,v,v,v,v,v,v,v,v)
return len(out)
print "a", a('xxxxxxxxxx')
print "b", b('xxxxxxxxxx')
print "c", c('xxxxxxxxxx')
print "d", d('xxxxxxxxxx')
import profile
profile.run("a('xxxxxxxxxx')")
profile.run("b('xxxxxxxxxx')")
profile.run("c('xxxxxxxxxx')")
profile.run("d('xxxxxxxxxx')")
More information about the Python-list
mailing list