Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Python list joining — include separator at the start or at the end

The output for ', '.join(['a', 'b', 'c', 'd']) is:

a, b, c, d

Is there a standard way in Python to achieve the following outputs instead?

# option 1, separator is also at the start
, a, b, c, d

# option 2, separator is also at the end
a, b, c, d, 

# option 3, separator is both at the start and the end
, a, b, c, d, 
like image 835
Jivan Avatar asked Jan 26 '23 15:01

Jivan


1 Answers

There is no standard approach, but a natural way is to add empty strings at the end or at the beginning (or at the end and the beginning). Using some more modern syntax:

>>> ', '.join(['', *['a', 'b', 'c', 'd']])
', a, b, c, d'
>>> ', '.join([*['a', 'b', 'c', 'd'], ''])
'a, b, c, d, '
>>> ', '.join(['', *['a', 'b', 'c', 'd'], ''])
', a, b, c, d, '

Or just use string formatting:

>>> sep = ','
>>> data = ['a', 'b', 'c', 'd']
>>> f"{sep}{sep.join(data)}"
',a,b,c,d'
>>> f"{sep.join(data)}{sep}"
'a,b,c,d,'
>>> f"{sep}{sep.join(data)}{sep}"
',a,b,c,d,'
like image 97
juanpa.arrivillaga Avatar answered Jan 29 '23 06:01

juanpa.arrivillaga