Reputation: 14581
I have used some example code that uses str() instead of my normal habit of '' to denote an empty string. Is there some advantage for using str()? Eg:
# .....
d = dict()
# .....
# .....
if v is None:
d[c.name] = str()
else:
d[c.name] = v
It does seem to be slower.
$ python -m timeit "'.'.join(str(n)+'' for n in range(100))"
100000 loops, best of 3: 12.9 usec per loop
$ python -m timeit "'.'.join(str(n)+str() for n in range(100))"
100000 loops, best of 3: 17.2 usec per loop
Upvotes: 9
Views: 1889
Reputation: 174624
Referring to the Python manual str()
is used when:
bytes
(or other byte sequence, like bytearray
) into a stringIn all other cases, you should use ''
.
The fact that an empty str()
call returns a blank string is a side effect and not the intended primary use of the method.
Upvotes: 6
Reputation: 798556
The only advantage is that if str
is redefined locally then str()
will use that definition whereas ''
will not. Otherwise, they are equivalent (although not equal since the compiler will emit a function call in one case and a literal in the other).
Upvotes: 7