Creating formatted output using picture strings
Arnaud Delobelle
arnodel at googlemail.com
Wed Feb 10 13:21:35 EST 2010
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