function that modifies a string

Jason tenax.raccoon at gmail.com
Mon Jul 10 00:21:36 EDT 2006


greenflame wrote:
> I want to make a function that does the following. I will call it
> thefunc for short.
>
> >>> s = "Char"
> >>> thefunc(s)
> >>> s
> '||Char>>'
>
> I tried the following
>
> def thefunc(s):
>     s = "||" + s + ">>"
>
> The problem is that if I look at the string after I apply the function
> to it, it is not modified. I realized that I am having issues with the
> scope of the variables. The string in the function, s, is local to the
> function and thus I am not changing the string that was inputed, but a
> copy. I cannot seem to figure out how to get what I want done. Thank
> you for your time.

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




More information about the Python-list mailing list