
Python join - list to string with space or comma
Python string has join()
method that concatenates all the elements of a Python list.
x = ['Python', 'Java', 'C']
y1 = '-'.join(x)
y2 = '*'.join(x)
y3 = ' '.join(x)
print(y1) # Python-Java-C
print(y2) # Python*Java*C
print(y3) # Python Java C
We can set a trailing comma in a list and it doesn't change the result of joining.
x1 = ['Mac', 'Book', 'Pro', ]
x2 = ['Mac', 'Book', 'Pro', '']
y1 = ','.join(x1)
y2 = ','.join(x2)
print(y1) # Mac,Book,Pro
print(y2) # Mac,Book,Pro,
The d
ends withs a comma because the last element of b
is an empty string.
Join a Python tuple or set
x1 = ('A', 'B', 'C')
x2 = {'A', 'B', 'C'}
y1 = '-'.join(x1)
y2 = '-'.join(x2)
print(y1) # A-B-C
print(y2) # B-C-A
join()
can take not only a list but a tuple or set. But the string concatenated from a set has a random "order" because a set doesn't have an order.
Comments
Powered by Markdown