Creating formatted output using picture strings

MRAB python at mrabarnett.plus.com
Wed Feb 10 11:02:54 EST 2010


Olof Bjarnason wrote:
> 2010/2/10 Peter Otten <__peter__ at web.de>:
>> python at bdurham.com wrote:
>>
>>> Does Python provide a way to format a string according to a
>>> 'picture' format?
>>>
>>> For example, if I have a string '123456789' and want it formatted
>>> like '(123)-45-(678)[9]', is there a module or function that will
>>> allow me to do this or do I need to code this type of
>>> transformation myself?
>> 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]'
>>
>> Peter
>> --
>> http://mail.python.org/mailman/listinfo/python-list
>>
> 
> Inspired by your answer here's another version:
> 
>>>> def picture(s, pic):
> ...   if len(s)==0: return pic
> ...   if pic[0]=='#': return s[0]+picture(s[1:], pic[1:])
> ...   return pic[0]+picture(s, pic[1:])
> ...
>>>> picture("123456789", "(###)-##-(###)[#]")
> '(123)-45-(678)[9]'
> 
Here's a version without recursion:

 >>> def picture(s, pic):
...     pic = pic.replace("%", "%%").replace("#", "%s")
...     return pic % tuple(s)
...
 >>> picture("123456789", "(###)-##-(###)[#]")
'(123)-45-(678)[9]'




More information about the Python-list mailing list