xxxxxxxxxx
# define a list of strings
my_list = ['Hello', 'world', '!']
# join the strings in the list into a single string with a space separator
result = ' '.join(my_list)
print(result) #print as Hello world !
# join the strings in the list into a single string with a dash separator
result = '-'.join(my_list)
print(result) #print as Hello-world-!
# join the strings in the list into a single string without a separator
result = ''.join(my_list)
print(result) #print as Helloworld!
xxxxxxxxxx
list = ['Add', 'Grepper', 'Answer']
Inline
> joined = " ".join(list)
> Add Grepper Answer
Variable
> seperator = ", "
> joined = seperator.join(list)
> Add, Grepper, Answer
xxxxxxxxxx
A more generic way to convert python lists to strings would be:
>>> xs = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
>>> ''.join(map(str, xs))
'12345678910'
xxxxxxxxxx
s = ['KDnuggets', 'is', 'a', 'fantastic', 'resource']
print(' '.join(s))
# Output
# KDnuggets is a fantastic resource
# if you want to join list elements with something other
# than whitespace in between? This thing may be a little bit stranger,
# but also easily accomplished.
s = ['Eleven', 'Mike', 'Dustin', 'Lucas', 'Will']
print(' and '.join(s))
# Ouptut
# Eleven and Mike and Dustin and Lucas and Will