Creating formatted output using picture strings

Stephen Hansen apt.shansen at gmail.com
Wed Feb 10 17:06:25 CET 2010


On Wed, Feb 10, 2010 at 1:45 AM, Peter Otten <__peter__ at web.de> wrote:

> A basic implementation without regular expressions:
>
> >>> def picture(s, pic, placeholder="@"):
> ...     parts = pic.split(placeholder)
> ...     result = [None]*(len(parts)+len(s))
> ...     result[::2] = parts
> ...     result[1::2] = s
> ...     return "".join(result)
> ...
> >>>
> >>> picture("123456789", "(@@@)-@@-(@@@)[@]")
> '(123)-45-(678)[9]'
>

Huh. This is the best version of those posted, I think (especially including
mine! My jumping to regex is worthy of shame, sh ame).

It took a little bit to figure out what was really going on here, but its a
single-pass through to do it without recursion or building a bunch of
intermediate strings that are concatenated and dropped away.

Its clever, and I don't mean that in the bad way, because -all- the
solutions are pretty clever in the sneaky-tricky-neat way. But this is
clever-cool.

Just slightly dark-voodoo-incantation-esque. Slightly!

--S
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <http://mail.python.org/pipermail/python-list/attachments/20100210/1bf48392/attachment.html>


More information about the Python-list mailing list