HiveBrain v1.2.0
Get Started
← Back to all entries
patternpythonCriticalCanonical

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

Submitted by: @import:stackoverflow-api··
0
Viewed 0 times
whylistjoinstringinstead

Problem

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

["Hello", "world"].join("-")


Than this:

"-".join(["Hello", "world"])


Is there a specific reason it is like this?

Solution

It's because any iterable can be joined (e.g, list, tuple, dict, set), but its contents and the "joiner" must be strings.

For example:

'_'.join(['welcome', 'to', 'stack', 'overflow'])
'_'.join(('welcome', 'to', 'stack', 'overflow'))


'welcome_to_stack_overflow'


Using something other than strings will raise the following error:

TypeError: sequence item 0: expected str instance, int found

Code Snippets

'_'.join(['welcome', 'to', 'stack', 'overflow'])
'_'.join(('welcome', 'to', 'stack', 'overflow'))
'welcome_to_stack_overflow'

Context

Stack Overflow Q#493819, score: 1480

Revisions (0)

No revisions yet.