3

I've inherited some Python code that constructs a string from the string arguments passed into __init__:

self.full_tag = prefix + number + point + suffix

Maybe I'm just over-thinking it but is this the best way to concatenate the arguments? I know it's possible to do something like:

self.full_tag = "".join([prefix, number, point, suffix])

Or just using string format function:

self.full_tag = '{}{}{}{}'.format(prefix, number, point, suffix)

What is the Python way of doing this?

2
  • 3
    All of these ways are OK. Generally, + is likely to be the least efficient (though you should timeit to be sure ;-). If it's not a bottleneck though, I'm not sure that any of the ways really matter too much. They're all fairly clear in what you're trying to accomplish with that line of code... Commented Sep 14, 2016 at 5:02
  • Nice, I see recommendations for each option. So I guess it depends. Commented Sep 14, 2016 at 7:25

2 Answers 2

3

Pythonic way is to follow The Zen of Python, which has several things to say about this case:

  • Beautiful is better than ugly.

  • Simple is better than complex.

  • Readability counts.

Add to that the famous quote by DonaldKnuth:

We should forget about small efficiencies, say about 97% of the time: premature optimization is the root of all evil.

With those in mind, the best of your choices is:

self.full_tag = prefix + number + point + suffix

Although, if number is really a number and point point is really a point, then this is more explicit:

self.full_tag = "%s%d.%s" % (prefix, number, suffix)
  • Explicit is better than implicit.
Sign up to request clarification or add additional context in comments.

4 Comments

"[str.format] is the new standard in Python 3, and should be preferred to the % formatting described in String Formatting Operations in new code." docs.python.org/2/library/stdtypes.html#str.format
@Alden that is correct, format seems to be endorsed by the creators of Python, but I personally still prefer the old printf syntax. Perhaps I am just old-fashioned, but it looks simpler and more readable to me.
With @Alden's point in mind, this is a very nice answer. For sake of completeness, here is a full link to PEP20.
@mwormser Thanks, I included the link in the answer.
2

The documentation recommends join for better performance over +:

6. ... For performance sensitive code, it is preferable to use the str.join() method which assures consistent linear concatenation performance across versions and implementations.

If performance is not too important, it's more of a matter of taste.

Personally, I find "".join cleaner and more readable than all of those braces in the format version.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.