How to join elements at the beginning and end of the list

Ned Batchelder ned at nedbatchelder.com
Tue Oct 31 11:49:32 EDT 2017


On 10/31/17 11:29 AM, Neil Cerutti wrote:
> On 2017-10-31, Ganesh Pal <ganesh1pal at gmail.com> wrote:
>> Here is my solution
>>
>>>>> values = '||' + '||'.join(map(str, value_list)) + '||'
>>>>> values
>> '||1||2||3||4||56||s||'
>>
>> I am joining the elements at the beginning and end of the list
>> using '+' operator any other solution, this is not looking
>> neater
>>
>> I am a Linux user using python 2.7
> You can use the % operator instead of +, and a generator
> expression instead of map. It's a pretty small improvement,
> though.
>
> values = '||%s||' % ('||'.join(str(s) for s in value_list))
>
> At least... I THINK you can use that generator expression in 2.7.
>

However you solve it, do yourself a favor and write a function to 
encapsulate it:

     def wrapped_join(values, sep):
         """Join values with sep, and also include sep at the ends."""
         return "{sep}{vals}{sep}".format(sep=sep, vals=sep.join(str(v) 
for v in values))

--Ned.



More information about the Python-list mailing list