Creating formatted output using picture strings

python at bdurham.com python at bdurham.com
Wed Feb 10 13:36:34 EST 2010


Arnaud,

Very cool!! Just when I thought the problem couldn't be made simpler ...
WOW!!!

Again, a big thank you to everyone who posted solutions!!!

I'm humbled at how clever and different everyone's techniques have been.

I have to say, I learned much more than I thought I needed to learn :)

Thanks again!

Malcolm

----- Original message -----
From: "Arnaud Delobelle" <arnodel at googlemail.com>
To: python-list at python.org
Date: Wed, 10 Feb 2010 18:21:35 +0000
Subject: Re: Creating formatted output using picture strings

python at bdurham.com writes:

> Original poster here.
>
> Thank you all for your ideas. I certainly learned some great techniques
> by studying everyone's solutions!!
>
> I was thinking that there was a built-in function for this common(?) use
> case which is why I shied away from writing my own in the first place
> ... hoping to not-reinvent the wheel, etc.
>
> Here's the solution I came up with myself. Its not as sexy as some of
> the posted solutions, but it does have the advantage of not failing when
> the number of input chars <> the number of placeholders in the pic
> string. I think it handles the edge cases pretty elegantly unless I'm
> too close to the details to miss the obvious.
>
> Any feedback on what follows would be appreciated.
>
> # format s using a picture string 
> # stops processing when runs out of chars in s or pic string
> # example: picture("123456789", "(@@@)-@@-(@@@)[@]")
> def picture( s, pic, placeholder="@" ):
>     s = list( s )
>     output = []
>     for sym in pic:
>         if sym <> placeholder:
>             output.append( sym )
>         elif len( s ):
>             output.append( s.pop( 0 ) )
>         else:
>             break
>     return ''.join( output )
>
> # test cases
> print picture("123456789", "(@@@)-@@-(@@@)[@]")
> print picture("123456789ABC", "(@@@)-@@-(@@@)[@]")
> print picture("1234", "(@@@)-@@-(@@@)[@]")
> print picture("123456789", "(@@@)-@@-(@@@)")
> print picture("123456789", "(@@@)-@@-(@@@)[@][@@@@@]")
> 	
> Regards,
> Malcolm

def picture(s, pic, placeholder='@'):
    nextchar=iter(s).next
    return ''.join(nextchar() if i == placeholder else i for i in pic)

passes all your test cases I think (I can't be sure because you didn't
post the expected output).  The trick is that when nextchar reaches the
end of the string 's', it raises a StopIteration which is caught by the
generator expression.

-- 
Arnaud



More information about the Python-list mailing list