osdir.com


[Date Prev][Date Next][Thread Prev][Thread Next][Date Index][Thread Index]

Python help needed


On 8/8/19 12:26 PM, Paolo G. Cantore wrote:

 > I think the special case treatment could be avoided.
 >
 > First: Join all items with ' and '
 > Second: Replace all ' and ' with ', ' except the last

That works great, until one of the elements of the original list is
"spam and eggs":

     >>> spam = ['apples', 'spam and eggs', 'bananas', 'tofu', 'cats']
     >>> s = " and ".join(spam)
     >>> s.replace(" and ", ", ", len(spam) - 2)  # except the last
     'apples, spam, eggs, bananas and tofu and cats'

Dan