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
-- 
http://mail.python.org/mailman/listinfo/python-list

Reply via email to