Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

python

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
like image 714
Martlark Avatar asked Jul 16 '18 02:07

Martlark


People also ask

Should I use repr or str?

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.

What is the difference between STR and string in Python?

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.

Why do we use str in Python?

The str() function converts the specified value into a string.

What is the purpose of __ Str__ method?

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.


2 Answers

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).

like image 132
Ignacio Vazquez-Abrams Avatar answered Oct 05 '22 15:10

Ignacio Vazquez-Abrams


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.

like image 22
Burhan Khalid Avatar answered Oct 05 '22 16:10

Burhan Khalid