2

I'm new to Python and I'm using Python3, I'm trying to join list items into a string, I found that when I try str().join(lst) I successfully get the list items as a string but when I do this str.join(lst) I get:

TypeError: descriptor 'join' requires a 'str' object but received a 'list'

What is the difference between str and str() in this case?

Henry Ecker
  • 34,399
  • 18
  • 41
  • 57
Ahmed Elsayed
  • 57
  • 1
  • 5
  • Occasionally you may actually see `str.join(lst)` if so watch out for code that assigns to `str` elsewhere e.g. `str = "hello"`. This "works" but is almost always a mistake. See also [Why can you assign values to built-in functions in Python?](https://stackoverflow.com/a/31865529/8379597) – jq170727 Sep 18 '17 at 04:48
  • `str()` is just a fancy obfuscation for `''`, i.e. creates an empty string. You could simply call `''.join(...)`. Whereas `str.join(...)` is an unbound reference to the string join() function. – smci Jan 14 '21 at 23:41

2 Answers2

6

str is a class. str() invokes that class's constructor and returns an instance of that class.

You typically want something like this anyway:

", ".join(...)

I suppose str().join(...) is the equivalent of "".join(...), but the latter is clearer to most Python developers.

user94559
  • 59,196
  • 6
  • 103
  • 103
  • 1
    +1. One might wanna add that the classmethod `str.join` additionally takes the separator string as the first argument, and only then the list as the second. That's where the TypeError comes from. – Jeronimo Sep 18 '17 at 04:51
2

join(list) is a class method of str class. str() is constructing an object (empty string object) of str class and it also have join method.

str().join(['abc', 'def']) will return abcdef and it is equivalent to ''.join(['abc', 'def']). What str() does it creating empty string object.

Class method join can also be used to generate the same result.
You can use str.join('', ['abc', 'def']) to generate the same output.

In summary, 'string'.join([string list]) is equivalent to str.join('string', [string list])

Ramesh-X
  • 4,853
  • 6
  • 46
  • 67