Replace every n instances of a string
Bengt Richter
bokr at oz.net
Fri Aug 15 22:33:21 EDT 2003
On 15 Aug 2003 14:25:57 -0700, thomasacross at hotmail.com (Tom Cross) wrote:
>Hello-
>
>I have a function that returns to me a text representation of Unicode
>data, which looks like this:
>
>\u0013\u0021\u003c\u003f\u0044\u001f\u006a\u005a\u0050\u0015\u0018\u001d\u007e\u006b\u004e\u007d\u006a\u006e\u0068\u0042\u0026\u003c\u004f\u0059\u0056\u002b\u001a\u0077\u0065\u006a\u000a\u0021\u005f\u0025\u003f\u0025\u0024\u007e\u0020\u0011\u0060\u002c\u0037\u0067\u007a\u0074\u0074\u0003\u0003\u000f\u0039\u0018\u0059\u0038\u0029\u0001\u0073\u0034\u0009\u0069\u005e\u0003\u006e\u000d\u004c\u001d\u00
>f\u006e\u001b\u006e\u0063\u000b\u0014\u0071\u007c\u004e\u006a\u0011\u004a\u001f\u0063\u0016\u003d\u0020\u0065\u003e\u0043\u0012\u0047\u0026\u0062\u0004\u0025\u003b\u0005\u004c\u002e\u005a\u0070\u0048
>
>I would like to add carriage returns to this for usability. But I
>don't want to add a return after each "\u" I encounter in the text
>(regexp comes to mind if I did). I want to add a return after each 12
>"\\u"s I encounter in the string.
>
>Any ideas? Do I not want to search for "\\u" but instead just insert
>a \n after each 72 characters (equivalent to 12 \uXXXX codes)? Would
>this provide better performance? If so, what would be the easiest way
>to do that?
>
>Thanks much!
If you are sure of the uniform format, you might try (testes as far as you see here ;-):
>>> def breakatn(s, n=72): return '\n'.join([s[i:i+n] for i in xrange(0,len(s),n)]+[''])
...
>>> print breakatn('0123456789'*20, 72)
012345678901234567890123456789012345678901234567890123456789012345678901
234567890123456789012345678901234567890123456789012345678901234567890123
45678901234567890123456789012345678901234567890123456789
>>> print breakatn('0123456789'*6, 25)
0123456789012345678901234
5678901234567890123456789
0123456789
The [''] is to get a last item for join to put a \n between it and what precedes.
Regards,
Bengt Richter
More information about the Python-list
mailing list