Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is there a difference between str function and percent operator in Python

When converting an object to a string in python, I saw two different idioms:

A: mystring = str(obj)

B: mystring = "%s" % obj

Is there a difference between those two? (Reading the Python docs, I would suspect no, because the latter case would implicitly call str(obj) to convert obj to a string.

If yes, when should I use which?

If no, which one should I prefer in "good" python code? (From the python philosophy "explicit over implicit", A would be considered the better one?)

like image 652
Stefan Winkler Avatar asked Sep 23 '16 16:09

Stefan Winkler


People also ask

What is str function in Python?

Python has a built-in string class named "str" with many handy features (there is an older module named "string" which you should not use). String literals can be enclosed by either double or single quotes, although single quotes are more commonly used.

What does %% mean in Python?

The % symbol in Python is called the Modulo Operator. It returns the remainder of dividing the left hand operand by right hand operand.


1 Answers

The second version does more work.

The %s operator calls str() on the value it interpolates, but it also has to parse the template string first to find the placeholder in the first place.

Unless your template string contains more text, there is no point in asking Python to spend more cycles on the "%s" % obj expression.

However, paradoxically, the str() conversion is, in practice, slower as looking up the name str() and pushing the stack to call the function takes more time than the string parsing:

>>> from timeit import timeit
>>> timeit('str(obj)', 'obj = 4.524')
0.32349491119384766
>>> timeit('"%s" % obj', 'obj = 4.524')
0.27424097061157227

You can recover most of that difference by binding str to a local name first:

>>> timeit('_str(obj)', 'obj = 4.524; _str = str')
0.28351712226867676

To most Python developers, using the string templating option is going to be confusing as str() is far more straightforward. Stick to the function unless you have a critical section that does a lot of string conversions.

like image 138
Martijn Pieters Avatar answered Oct 24 '22 07:10

Martijn Pieters