Format Code Repeat Counts?

MRAB python at mrabarnett.plus.com
Thu Aug 13 00:19:18 CEST 2009


jschwab wrote:
> Are repeat counts supported Python's str.format() in some fashion?
> 
> In Fortran my format strings can have repeat counts.
> 
> <pseudocode>
> write(*, fmt="3F8.3") [1, 2, 3]
>    1.000  2.000   3.000
> </pseudocode>
> 
> I don't think printf-style format codes, which is what'd I'd
> previously used in Python, allow for repeat counts.
> 
> 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?
> 
The shortest I can come up with is:

     "[" + "][".join(letters) + "]"




More information about the Python-list mailing list