function that modifies a string
Simon Forman
rogue_pedro at yahoo.com
Mon Jul 10 02:35:32 EDT 2006
greenflame wrote:
> Jason wrote:
> >
> > There /are/ a few hacks which will do what you want. However, if you
> > really need it, then you probably need to rethink your program design.
> > Remember, you can't change a string since a string is immutable! You
> > can change a variable to bind to another string. In the following
> > example, s gets rebound to the new string while t keeps the original
> > string value:
> >
> > >>> def changeString(varName):
> > ... globalDict = globals()
> > ... globalDict[varName] = '||' + globalDict[varName] + '>>'
> > ... return
> > ...
> > >>> s = 'Char'
> > >>> t = s
> > >>> changeString('s')
> > >>> s
> > '||Char>>'
> > >>> t
> > 'Char'
> >
> > Further note that this only affects variables in the global scope. I
> > hope this helps!
> >
> > --Jason
>
> Ok so let me see if I understand. The globalDict is just a dictionary
> containing the name of the global variables as the keys and their
> values as the values of the dictionary? Thus the inputed variable is
> treated like a global variable?
The answer to your first question is yup! You've got it. That's what
the globals() function returns. (There is also a function locals()
that returns a similar dict but for locals.)
The answer to your second question is no. The inputed *name* (the
changeString() function must be passed a string, not a variable) must
be the name of an object in the global scope for the function to work.
You almost certainly want to use a function like the thefunc() function
that Jason posted.
One other thing, you could define it like so:
def thefunc(s):
return '||%s>>' % s
Peace,
~Simon
More information about the Python-list
mailing list