Groups | Search | Server Info | Keyboard shortcuts | Login | Register [http] [https] [nntp] [nntps]
Groups > comp.lang.python > #17322
| From | Terry Reedy <tjreedy@udel.edu> |
|---|---|
| Subject | Re: How to generate "a, b, c, and d"? |
| Date | 2011-12-15 19:57 -0500 |
| References | <9393353.282.1323967703697.JavaMail.geo-discussion-forums@vbyc2> <4EEA2DF2.9080107@mrabarnett.plus.com> |
| Newsgroups | comp.lang.python |
| Message-ID | <mailman.3708.1323997066.27778.python-list@python.org> (permalink) |
On 12/15/2011 12:27 PM, MRAB wrote:
> On 15/12/2011 16:48, Roy Smith wrote:
>> I've got a list, ['a', 'b', 'c', 'd']. I want to generate the string,
>> "a, b, c, and d" (I'll settle for no comma after 'c'). Is there some
>> standard way to do this, handling all the special cases?
>>
>> [] ==> ''
>> ['a'] ==> 'a'
>> ['a', 'b'] ==> 'a and b'
>> ['a', 'b', 'c', 'd'] ==> 'a, b, and c'
>>
>> It seems like the kind of thing django.contrib.humanize would handle,
>> but alas, it doesn't.
>
> How about this:
>
> def and_list(items):
> if len(items) <= 2:
> return " and ".join(items)
>
> return ", ".join(items[ : -1]) + ", and " + items[-1]
To avoid making a slice copy,
last = items.pop()
return ", ".join(items) + (", and " + last)
I parenthesized the last two small items to avoid copying the long
string twice with two appends. Even better is
items[-1] = "and " + items[-1]
return ", ".join(items)
so the entire output is created in one operation with no copy.
But I would only mutate the list if I started with
items = list(iterable)
where iterable was the input, so I was mutating a private copy.
--
Terry Jan Reedy
Back to comp.lang.python | Previous | Next — Previous in thread | Next in thread | Find similar | Unroll thread
How to generate "a, b, c, and d"? Roy Smith <roy@panix.com> - 2011-12-15 08:48 -0800
Re: How to generate "a, b, c, and d"? MRAB <python@mrabarnett.plus.com> - 2011-12-15 17:27 +0000
Re: How to generate "a, b, c, and d"? Tim Chase <python.list@tim.thechases.com> - 2011-12-15 12:01 -0600
Re: How to generate "a, b, c, and d"? Ethan Furman <ethan@stoneleaf.us> - 2011-12-15 10:19 -0800
Re: How to generate "a, b, c, and d"? Tim Chase <python.list@tim.thechases.com> - 2011-12-15 12:51 -0600
Re: How to generate "a, b, c, and d"? Roy Smith <roy@panix.com> - 2011-12-15 11:01 -0800
Re: How to generate "a, b, c, and d"? Roy Smith <roy@panix.com> - 2011-12-15 11:01 -0800
Re: How to generate "a, b, c, and d"? MRAB <python@mrabarnett.plus.com> - 2011-12-15 19:27 +0000
Re: How to generate "a, b, c, and d"? Ian Kelly <ian.g.kelly@gmail.com> - 2011-12-15 14:22 -0700
Re: How to generate "a, b, c, and d"? Terry Reedy <tjreedy@udel.edu> - 2011-12-15 19:57 -0500
Re: How to generate "a, b, c, and d"? Chris Angelico <rosuav@gmail.com> - 2011-12-16 13:42 +1100
Re: How to generate "a, b, c, and d"? Terry Reedy <tjreedy@udel.edu> - 2011-12-16 00:26 -0500
csiph-web