Intellipaat Back

Explore Courses Blog Tutorials Interview Questions
+3 votes
3 views
in Python by (3.5k points)
edited by

I am confused about the usage of string.join(list) instead of list.join(string), for instance see this code:

    my_list = ["Hey", "Fish"]
    print my_list.join("-")
    # Produce: "Hey-Fish"

I think this code seems nicer than this one:

    my_list = ["Hey", "Fish"]
    print "-".join(my_list)
    # Produce: "Hey-Fish"

Can someone tell me the reason behind this? 

2 Answers

0 votes
by (46k points)
edited by

the reason behind this is that we can join iterable, not only list, result and 'joiner' are always strings too. E.g.

 import urllib2

print '\n###########\n'.join(
    urllib2.urlopen('https://intellipaat.com/community
'))

0 votes
by (106k points)

Primarily because the result of some String.join() is a string.

The sequence (list or tuple or whatever) doesn't appear in the result, just a string. Because the result is a string, it makes sense as a method of a string.

You can use the following video tutorials to clear all your doubts:-

Related questions

0 votes
4 answers
0 votes
1 answer
+1 vote
2 answers
+3 votes
2 answers

31k questions

32.8k answers

501 comments

693 users

Browse Categories

...