Creating formatted output using picture strings
Peter Otten
__peter__ at web.de
Wed Feb 10 04:45:37 EST 2010
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
More information about the Python-list
mailing list