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,
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,'
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With