78

I've been using string.join() method in python 2 but it seems like it has been removed in python 3. What is the equivalent method in python 3?

string.join() method let me combine multiple strings together with a string in between every other string. For example, string.join(("a", "b", "c"), ".") would result "a.b.c".

Fred Foo
  • 355,277
  • 75
  • 744
  • 836
Dennis
  • 3,506
  • 5
  • 34
  • 42
  • 8
    `string.join` is deprecated in Python 2. So you would use `'.'.join()` in Python 2 too. – rubik Dec 29 '11 at 13:09
  • Alright I'll keep that in mind :) – Dennis Dec 29 '11 at 13:21
  • @rubik that is of course unless you `import string` ;) – BoltzmannBrain Jul 08 '15 at 21:10
  • @alavin89 I'm sorry but I don't understand what you are saying. *All* the string functions that became methods are deprecated. Whether you import the module or not. – rubik Jul 09 '15 at 05:54
  • 1
    @rubrik `string` methods are deprecated in favor of `str` methods. In most cases you want to use your pythonic `'.'.join()` approach, but there are legitimate, pythonic uses for `str.join()` (formerly `string.join()`) too. For example, you sometimes want the *joining str* to be configurable at runtime and want to pass the function (along with the *joining str*) on to other elements of a string-processing or NLP pipeline. – hobs Sep 12 '16 at 18:28

4 Answers4

76

'.'.join() or ".".join().. So any string instance has the method join()

Tim
  • 19,793
  • 8
  • 70
  • 95
38

str.join() works fine in Python 3, you just need to get the order of the arguments correct

>>> str.join('.', ('a', 'b', 'c'))
'a.b.c'
hobs
  • 18,473
  • 10
  • 83
  • 106
  • 4
    ... and that is because generally `obj.method(args)` is technically equivalent to the `objclass.method(obj, args)`. My +1. Anyway, the Tim's is more usual in Python. – pepr Jan 14 '14 at 23:17
  • 1
    Yea, thanks. I personally use @Tim's approach too, when I can. But sometimes you need the `join` function before you have the delimiter string instantiated (to pass to a middleware constructor, serializer, etc). And @Dennis was looking for the Python3-equivalent to `string.join`, and this is the only one that I'm aware of. – hobs Jan 14 '14 at 23:43
  • Yes. I understand the motivation. This is absolutely correct ;) – pepr Jan 14 '14 at 23:57
15

There are method join for string objects:

".".join(("a","b","c"))

werewindle
  • 3,009
  • 17
  • 27
4

Visit https://www.tutorialspoint.com/python/string_join.htm

s=" "
seq=["ab", "cd", "ef"]
print(s.join(seq))

ab cd ef

s="."
print(s.join(seq))

ab.cd.ef

cbuchart
  • 10,847
  • 9
  • 53
  • 93
Jamil Ahmad
  • 107
  • 1
  • 1