Newbie asks: How to translate this line of C to Py

James Logajan JamesL at Lugoj.Com
Tue Jul 10 11:31:27 EDT 2001


Fredrik Lundh wrote:
> 
> Steve S.L. Wong wrote:
> 
> > while (command = strtok(line_ptr,";"),line_ptr=0,command) {
> > }
> 
> ouch.  that's ugly.  ever heard of for-loops?  and did you miss
> the "Never use this function" sentence in your C library manual? ;-)
> 
> anyway, this is a pretty good emulation:
> 
> for command in line.split(";"):
>     ...

I'm pretty sure that is NOT equivalent. The strtok is treating ";" as
whitespace whereas split is treating ";" as a delimiter. The difference
shows up when more than one whitespace/delimiter are adjacent. So
"this;;code;" parses to:

[ "this", "", "code", ""]

But a proper strtok equivalent should give:

[ "this", "code" ]

That is why I added a filter to my example. On the other hand, I'm guessing
the actual application from whence that C code comes really needs to treat
the semicolon as a delimiter.



More information about the Python-list mailing list