Suppose I have this list:
lis = ['a','b','c','d']
If I do 'x'.join(lis)
the result is:
'axbxcxd'
What would be a clean, simple way to get this output?
'xaxbxcxdx'
I could write a helper function:
def joiner(s, it):
return s+s.join(it)+s
and call it like joiner('x',lis)
which returns xaxbxcxdx
, but it doesn't look as clean as it could be. Is there a better way to get this result?
You can use split() function to split a string based on a delimiter to a list of strings. You can use join() function to join a list of strings based on a delimiter to give a single string.
Concatenation is the process of appending one string to the end of another string. You concatenate strings by using the + operator. For string literals and string constants, concatenation occurs at compile time; no run-time concatenation occurs. For string variables, concatenation occurs only at run time.
The join() method takes all items in an iterable and joins them into one string. A string must be specified as the separator.
>>> '{1}{0}{1}'.format(s.join(lis), s)
'xaxbxcxdx'
You can join a list that begins and ends with an empty string:
>>> 'x'.join(['', *lis, ''])
'xaxbxcxdx'
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