Creating formatted output using picture strings

python at bdurham.com python at bdurham.com
Wed Feb 10 13:30:21 EST 2010


Hi Tim,

Thank you very much for your update to MRAB's creative solution.

> You don't give the expected output for these test cases, so 
> it's hard to tell whether you want to pad-left or pad-right.

To be honest, I wasn't sure myself :)

My original post was the result of doing some simple formatting where my
input strings were 'guaranteed'<g> to be a consistent length. I hadn't
started to think about the specs for a more universal picture function
until I started to study and test the solutions proposed by others. It
bears repeating again - what a clever mix of techniques - I really
learned a lot more than I was expecting!

I appreciate you taking the extra time to analyze the problem and refine
it further.

Cheers,
Malcolm

Riffing on MRAB's lovely solution, you can do something like

   def picture(
       s, pic,
       placeholder='@',
       padding=' ',
       pad_left=True
       ):
     assert placeholder != '%'
     s = str(s)
     expected = pic.count(placeholder)
     if len(s) > expected:
       s = s[:expected]
     if len(s) < expected:
       if pad_left:
         s = s.rjust(expected, padding)
       else:
         s = s.ljust(expected, padding)
     return pic.replace(
       '%', '%%').replace(
       placeholder, '%s') % tuple(s)

print picture("123456789", "(@@@)-@@-(@@@)[@]", pad_left=False)
print picture("123456789ABC", "(@@@)-@@-(@@@)[@]", pad_left=False)
print picture("1234", "(@@@)-@@-(@@@)[@]", pad_left=False)
print picture("123456789", "(@@@)-@@-(@@@)", pad_left=False)
print picture("123456789", "(@@@)-@@-(@@@)[@][@@@@@]", 
pad_left=False)

That way you can specify your placeholder, your padding 
character, and whether you want it to pad to the left or right.



More information about the Python-list mailing list