Python join: why is it string.join(list) instead of list.join(string)?

0 votes

This has always confused me. It seems like this would be nicer:

my_list = ["Hello", "world"]
print my_list.join("-")
# Produce: "Hello-world"

Than this:

my_list = ["Hello", "world"]
print "-".join(my_list)
# Produce: "Hello-world"

Is there a specific reason it is like this?

May 14, 2018 in Python by anonymous
38 views

1 answer to this question.

0 votes

950down voteaccepted

It's because any iterable can be joined, not just lists, but the result and the "joiner" are always strings.

E.G:

import urllib2
print '\n############\n'.join(
    urllib2.urlopen('http://data.stackexchange.com/users/7095'))
answered May 15, 2018 by ariaholic
• 7,340 points

Related Questions In Python

0 votes
1 answer

Python join: why is it string.join(list) instead of list.join(string)?

This is because join is a "string" ...READ MORE

answered Jul 30, 2018 in Python by Priyaj
• 56,520 points
66 views
0 votes
1 answer

Convert string list of dict from csv into JSON object in python

You can use the ast module Ex: import ast s = """[{'10': ...READ MORE

answered Sep 12, 2018 in Python by Priyaj
• 56,520 points
442 views
0 votes
1 answer

Convert string list of dict from csv into JSON object in python

You can use the ast module Ex: import ast s = """[{'10': ...READ MORE

answered Sep 24, 2018 in Python by Priyaj
• 56,520 points
64 views
0 votes
1 answer

Why is Python scoping made the way it is?

The likeliest answer is that it just ...READ MORE

answered Nov 5, 2018 in Python by Nymeria
• 3,520 points

edited Dec 17, 2018 by Nymeria 31 views
0 votes
1 answer

What is the recommended way to randomize a list of strings using Python?

Hi. Nice question. Here is the simplified answer ...READ MORE

answered Jan 18 in Python by Nymeria
• 3,520 points
49 views
0 votes
1 answer

How to zip with a list output in Python instead of a tuple output?

Good question - Considering that you are ...READ MORE

answered Feb 7 in Python by Nymeria
• 3,520 points
43 views
0 votes
1 answer

Is it enough to only create checksum of a zip package instead of each file?

I assume you are asking about the ...READ MORE

answered May 8 in Python by SDeb
• 13,160 points
18 views
0 votes
1 answer

Is there a way to list out in-built variables and functions of Python?

The in-built variables and functions are defined ...READ MORE

answered May 14 in Python by Junaid
34 views
0 votes
1 answer

How to get the size of a string in Python?

If you are talking about the length ...READ MORE

answered Jun 4, 2018 in Python by ariaholic
• 7,340 points
90 views
+2 votes
6 answers

What exactly is the function of random.seed() in python?

The seed method is used to initialize the ...READ MORE

answered Oct 29, 2018 in Python by Rahul
19,401 views