function that modifies a string
greenflame
alikakakhel at yahoo.com
Mon Jul 10 00:54:35 EDT 2006
Jason wrote:
>
> You cannot do what you are trying to do directly. Strings are
> immutable objects. Once a string is created, that string cannot be
> modified. When you operate on a string, you produce a different
> string. Functions which operate on a string should return their value:
>
> >>> def thefunc(s):
> ... return '||' + s + '>>'
> ...
> >>> s = 'Char'
> >>> s = thefunc(s)
> >>> s
> '||Char>>'
>
> 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?
More information about the Python-list
mailing list