Format Code Repeat Counts?

MRAB python at mrabarnett.plus.com
Thu Aug 13 00:38:44 CEST 2009


Chris Rebert wrote:
> On Wed, Aug 12, 2009 at 4:34 PM, jschwab<jschwab at gmail.com> wrote:
> <snip>
>> As a more concrete example, say I have several sets of letters in a
>> list of strings
>>     letters = ["aeiou", "hnopty", "egs", "amsp"]
>> and I wanted to build a regular expression string out of them like
>>     re_str <==> "[aeiou][hnopty][egs][amsp]"
>> Right now, the best I've got that doesn't require an explicit string
>> like "[{1}][{2}][{3}][{4}]" is
>>     re_str = "".join(map(lambda x: "[{0}]".format(x), letters))
>>
>> Is there a better way?
> 
> Slightly better, by using a generator expression instead of map() and lambda:
> re_str = "".join("[{0}]".format(x) for x in letters)
> 
> Though obviously MRAB's is shorter (and a good show of lateral thinking).
> 
Python 3.1 supports auto-numbered placeholders "[{}]", so:

     re_str = ("[{}]" * len(letters)).format(*letters)



More information about the Python-list mailing list