[Tutor] Re: counting space-delimited strings within a sequence
Andrei
project5 at redrival.net
Fri Apr 2 16:50:10 EST 2004
Vicki Stanfield wrote on Fri, 2 Apr 2004 16:33:28 -0500 (EST):
> This is probably a very simple question, but I am not sure of the best way
> to handle it. I am attempting to determine the number of parameters that
> are passed into my function.
<snip>
Wouldn't it be easier to pass real parameters instead of a string
containing parameters separated by spaces? Something like this works very
well if you don't know in advance how many arguments you will have:
>>> def myfunc(*args):
... for arg in args:
... print arg
...
>>> myfunc('a', 'b', 3)
a
b
3
>>> myfunc(1)
1
> There might be none. I wrote the following:
>
> i=0
> args = parameters.split(" ")
You don't need to specify ' ' as argument for split(), because split()
without arguments by default splits at whitespaces.
> for count in args:
> i+=1
In order to determine the length of an array, you can use the len()
function, which is a lot easier than looping over an array and increasing a
counter:
self.numparams = len(args)
By the way, this code works just fine with the "*args" trick I mentioned
above.
> but if there are no parameters, self.numparams is still set to 1 instead
> of 0. I don't understand, but when I run this in idle, I get the same
> result. How do I split up a string of words which are space-delimited and
> handle the empty string as well? And yes, I'm sure that I'm just missing
> some fundamental Pythonism.
Leave out the parameter you pass to split:
>>> ''.split(' ')
[''] # 1 parameter (being an empty string)
>>> ''.split()
[] # no paramaters
--
Yours,
Andrei
=====
Real contact info (decode with rot13):
cebwrpg5 at jnanqbb.ay. Fcnz-serr! Cyrnfr qb abg hfr va choyvp cbfgf. V ernq
gur yvfg, fb gurer'f ab arrq gb PP.
More information about the Tutor
mailing list