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
The difference between str() and repr() is: The str() function returns a user-friendly description of an object. The repr() method returns a developer-friendly string representation of an object.
str is a built-in function (actually a class) which converts its argument to a string. string is a module which provides common string operations. Put another way, str objects are a textual representation of some object o , often created by calling str(o) . These objects have certain methods defined on them.
The str() function converts the specified value into a string.
Python __str__() This method returns the string representation of the object. This method is called when print() or str() function is invoked on an object.
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).
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With