[Chicago] constant length string manipulation

Ian Bicking ianb at colorstudy.com
Thu Nov 29 23:42:15 CET 2007


Ed Leafe wrote:
> On Nov 29, 2007, at 4:45 PM, Ian Bicking wrote:
> 
>> def fivespaces(s):
>>      while len(s) < 5:
>>          s += ' '
>>      while len(s) > 5:
>>          s = s[:-1]
>>      return s
> 
> 	Why not just: return s.ljust(5)[:5]

Because that's stupid!  Now *this* is smart:


PyDoc_STRVAR(pad5__doc__, "pad5 module\n");

static PyObject *
pad5(PyObject *self, PyObject *args)
{
   int s_len, i;
   char *s;
   char buf[5];
   if (!PyArg_ParseTuple(args, "s#:pad5", &s, &s_len))
     return NULL;
   strncpy(buf, s, s_len < 5 ? s_len : 5);
   if (s_len < 5)
     for (i=s_len; i<5; i++)
       buf[i] = ' ';
   return Py_BuildValue('s#', buf, 5);
}

static PyMethodDef methods[] = {
   {"pad5", pad5, METH_VARARGS,
    "pad5(string) ->\n\
Return the string padding or truncated to 5 characters."},
   {NULL, NULL},
};

PyMODINIT_FUNC
initpad5(void)
{
   Py_InitModule3("pad5", methods, pad5__doc__);
}


Admittedly I have not tried compiling it.  But no doubt it is *blazing 
fast*!!!!!!!

-- 
Ian Bicking : ianb at colorstudy.com : http://blog.ianbicking.org


More information about the Chicago mailing list