How do I turn a list into a string in Python?
Short answer
Use separator.join(items). The separator is the string you call the method on, and every item must already be a string.
tracks = ["Python", "PHP", "Ruby"]
", ".join(tracks) # 'Python, PHP, Ruby'
"".join(tracks) # 'PythonPHPRuby'
"\n".join(tracks) # each on its own lineThe syntax looks backwards until you notice why: the separator is what does the joining, and it works with any iterable, not just lists.
#The error everyone hits first
", ".join([1, 2, 3])
# TypeError: sequence item 0: expected str instance, int foundjoin will not convert for you. Map first:
", ".join(str(n) for n in [1, 2, 3]) # '1, 2, 3'
", ".join(map(str, [1, 2, 3])) # same thing#Why not just concatenate in a loop?
result = ""
for item in tracks:
result += item + ", " # slow, and leaves a trailing commaStrings are immutable, so every += builds a whole new string. On a big list that is quadratic work. join allocates once.
#Going the other way
"Python, PHP, Ruby".split(", ") # ['Python', 'PHP', 'Ruby']
"a b c".split() # ['a', 'b', 'c'] — any whitespace, no empties
"a,b,c".split(",", 1) # ['a', 'b,c'] — split at most onceNote that bare .split() with no argument collapses runs of whitespace and drops empty strings, which is usually what you want for prose.