Posted By: Evan Fosmark
This has always confused me. It seems like this would be nicer:
my_list = ["Hello", "world"] print(my_list.join("-")) # Produce: "Hello-world"
my_list = ["Hello", "world"] print("-".join(my_list)) # Produce: "Hello-world"
Is there a specific reason it is like this?
It’s because any iterable can be joined (e.g, list, tuple, dict, set), but its contents and the "joiner" must be strings.
'_'.join(['welcome', 'to', 'stack', 'overflow']) '_'.join(('welcome', 'to', 'stack', 'overflow'))
Using something other than strings will raise the following error:
TypeError: sequence item 0: expected str instance, int found