Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Join string before, between, and after

Tags:

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?

like image 909
Joe Frambach Avatar asked Jul 16 '13 17:07

Joe Frambach


People also ask

What split () & join () method Why & Where it is used?

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.

Can strings be joined together?

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.

How do you join strings?

The join() method takes all items in an iterable and joins them into one string. A string must be specified as the separator.


2 Answers

>>> '{1}{0}{1}'.format(s.join(lis), s)
'xaxbxcxdx'
like image 51
arshajii Avatar answered Oct 19 '22 08:10

arshajii


You can join a list that begins and ends with an empty string:

>>> 'x'.join(['', *lis, ''])
'xaxbxcxdx'
like image 39
chepner Avatar answered Oct 19 '22 09:10

chepner