Python help needed

Dan Sommers 2QdxY4RzWzUUiLuE at potatochowder.com
Thu Aug 8 13:29:23 EDT 2019


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



More information about the Python-list mailing list