Martlark
Martlark

Reputation: 14581

Python str() vs. '' - which is preferred

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

Answers (2)

Burhan Khalid
Burhan Khalid

Reputation: 174624

Referring to the Python manual str() is used when:

  1. You want the string representation of an object
  2. You want to convert bytes (or other byte sequence, like bytearray) into a string

In 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

Ignacio Vazquez-Abrams
Ignacio Vazquez-Abrams

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

Related Questions