Replacing last comma in 'C1, C2, C3' with 'and' so that it reads'C1, C2 and C3'
bokr at oz.net
Tue Jul 12 22:46:16 CEST 2005
On Wed, 13 Jul 2005 03:47:07 +0800, "Ric Da Force" <ric at next-level.com.au> wrote:
>Thank you all for your input! It was good to see so much convergence in the
>approach! Again, I think that it speaks loudly for the concise way of doing
>thins in Python... Anyway, I have typed in all of the solutions and have
>gained a great understanding of how to do this in future.
>"Brian van den Broek" <bvande at po-box.mcgill.ca> wrote in message
>news:mailman.1635.1121152323.10512.python-list at python.org...
>> Ric Da Force said unto the world upon 12/07/2005 02:43:
>>> I have a string such as 'C1, C2, C3'. Without assuming that each bit of
>>> text is of fixed size, what is the easiest way to change this list so
>>> that it reads:
>>> 'C1, C2 and C3' regardless of the length of the string.
>>> Regards and sorry for the newbie question,
>> Hi Ric,
>> the rsplit method of strings should get you going:
>> >>> data = "the first bit, then the second, finally the third"
>> >>> chunks = data.rsplit(',', 1)
>> >>> chunks
>> ['the first bit, then the second', ' finally the third']
>> Brian vdB
Or, to finish Brian's solution by inserting the ", and" in place of the "," :
>>> data = "the first bit, then the second, finally the third"
>>> ', and'.join(data.rsplit(',',1))
'the first bit, then the second, and finally the third'
>>> ', and'.join('C1, C2, C3'.rsplit(',',1))
'C1, C2, and C3'
More information about the Python-list