Creating formatted output using picture strings
arnodel at googlemail.com
Wed Feb 10 19:21:35 CET 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 ) )
> return ''.join( output )
> # test cases
> print picture("123456789", "(@@@)-@@-(@@@)[@]")
> print picture("123456789ABC", "(@@@)-@@-(@@@)[@]")
> print picture("1234", "(@@@)-@@-(@@@)[@]")
> print picture("123456789", "(@@@)-@@-(@@@)")
> print picture("123456789", "(@@@)-@@-(@@@)[@][@@@@@]")
def picture(s, pic, placeholder='@'):
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
More information about the Python-list