unreferenced (???) variable; prob. simple

Andy Jewell andy at wild-flower.co.uk
Mon Sep 15 17:32:21 EDT 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
>             break
>         break
>     for b in range(1, length+1):
>         if inpstr[-b] not in spacelst:
>             endind = length-b
>             break
>         break
>     stripstring = inpstr[begind:(endind+1)]
>     print stripstring
>     print begind
>     print endind
>
> if __name__ == '__main__':
>     stripfunc()

Halfdan,

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:

-----8<-----
>>> def strp(strg):
	from string import whitespace
	b=0
	while b<len(strg) and strg[b] in whitespace:
		b+=1
	e=len(strg)-1
	while e>b and strg[e] in whitespace:
		e-=1
	return strg[b:e+1]

>>> strp("\t\n this is a test \r\t")
'this is a test'
>>> 
-----8<-----


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() ;-))

!bing!  idea:

def strp2(strg):
	return strg.split().join(" ")

_However_ this will also remove duplicate spaces and any other whitespace in 
strg... maybe even useful!

hth
-andyj





More information about the Python-list mailing list