unreferenced (???) variable; prob. simple
andy at wild-flower.co.uk
Mon Sep 15 23:32:21 CEST 2003
On Monday 15 Sep 2003 8:31 pm, Halfdan Holger Knudsen wrote:
> goodday all - here's a snippet of code that just doesn't seem to work...at
> all! But I haven't got the faintest idea why I keep getting an unref.
> local var. error. Take a look - I know I can get good help here. And PS:
> Thanks beforehand.
> If you're wondering - it's an attempt at a (crude) reproduction of the
> string.split() functionality for learning purposes.
> #! /usr/bin/env python
> import string
> begind = 0
> endind = 0
> def stripfunc():
> inpstr = raw_input('String to strip: ')
> length = len(inpstr)
> spacelst = list(string.whitespace)
> print spacelst
> for a in range(length):
> if inpstr[a] not in spacelst:
> begind = a
> for b in range(1, length+1):
> if inpstr[-b] not in spacelst:
> endind = length-b
> stripstring = inpstr[begind:(endind+1)]
> print stripstring
> print begind
> print endind
> if __name__ == '__main__':
I reckon it's due to your 'excessive use' ;-) of 'break'. Basically, neither
of your for loops ever go more than one iteration, and if the first or last
character of your string is not whitespace, your *local* variables begind and
endind never get assigned anything (that's what Python said, right? ;-)).
Try this for size:
>>> def strp(strg):
from string import whitespace
while b<len(strg) and strg[b] in whitespace:
while e>b and strg[e] in whitespace:
>>> strp("\t\n this is a test \r\t")
'this is a test'
btw, string.split does this:
>>> "\t\n this is a test \r\t".split()
['this', 'is', 'a', 'test']
but I guessed you meant string.split() ;-))
return strg.split().join(" ")
_However_ this will also remove duplicate spaces and any other whitespace in
strg... maybe even useful!
More information about the Python-list