-3

I was studying PEP8's Programming Recommendations.

It was recommended to use ''.join to combine strings, but I did not understand when to do so:

  1. Should I concatenate every time that way?
  2. How useful is this?
  3. At what times are ideal to use join() to String? In Path, URL, Texts?

In [PEP 484](https://www.python.org/dev/peps/pep-0484/ Should this have been return ' '.join('Hello', name) ?

Bruno Campos
  • 595
  • 1
  • 7
  • 18
  • Use `str.join` for large strings. In particular, if constructing a large string, first create a list, then use `str.join` on it instead of using `+=` on an (at first) empty string. – iz_ May 17 '19 at 03:57

1 Answers1

2

Imagine you have four strings: a, b, c and d.

Say you want their concatenation, e = a + b + c + d. However, the + operator is only defined for two operands, so you would apparently need to concatenate the individual strings one by one.

The naive way to calculate this might be the following:

e = ((a + b) + c) + d

But this is inefficient, because it generates two throwaway strings: a + b and a + b + c.

Now, imagine we created a buffer-like object holding all the characters we wanted to combine:

e_buffer = [a, b, c, d]

We could create e from this all at once, avoiding the need to create many intermediate strings.

This requires a function, which, in Python, we call join; it is a method of a str, and intersperses that string between the arguments provided. Therefore, when you execute some_separator.join([a, b, c]), you get, in effect, a + some_separator + b + some_separator + c.

To answer your question: in general, when concatenating many strings, it should be faster to use join, and it will at least be more readable, especially when using a separator. For the case given in the question, I would instead use an f-string:

def greeting(name: str) -> str:
    return f'Hello {name}'
gmds
  • 19,325
  • 4
  • 32
  • 58
  • 1
    For a case like this, `+` is fine. The real problems start happening when you concatenate strings with `+` or `+=` in a *loop*, where you're likely to have far more than 4 strings to concatenate. – user2357112 May 17 '19 at 04:21