Sunday, 30 July 2017

python - Why is it string.join(list) instead of list.join(string)?



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?


Answer




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



For example:



import urllib2
print('\n############\n'.join(
urllib2.urlopen('http://data.stackexchange.com/users/7095')))

No comments:

Post a Comment

casting - Why wasn't Tobey Maguire in The Amazing Spider-Man? - Movies & TV

In the Spider-Man franchise, Tobey Maguire is an outstanding performer as a Spider-Man and also reprised his role in the sequels Spider-Man...