Modify a string's value
s0suk3 at gmail.com
s0suk3 at gmail.com
Wed Jul 16 00:32:49 EDT 2008
On Jul 15, 6:46 pm, Larry Bates <larry.ba... at websafe.com`> wrote:
> s0s... at gmail.com wrote:
> > Hi everyone,
>
> > I've heard that a 'str' object is immutable. But is there *any* way to
> > modify a string's internal value?
>
> > Thanks,
> > Sebastian
>
> Why would you care? Just create a new string (with the changed contents) and
> let garbage collection take care of the old one when all the references to it
> have gone away. Since these types of questions seem to appear almost every day
> on this list, this Python stuff is so much different than old languages people
> have hard time making the conceptual "jump". You can basically quite worrying
> about how/where things are stored, they just are.
>
Thanks for the reply. It's not that I'm having a hard time learning
Python. I've been programming it for some time. I just came across
this unusual situation where I'd like to modify a string passed to a
function, which seems impossible since Python passes arguments by
value. (Whereas in C, you'd customarily pass a pointer to the first
character in the string.)
I was playing around trying to simulate C++-like stream operations:
import sys
from os import linesep as endl
class PythonCout:
def __lshift__(self, obj):
sys.stdout.write(str(obj))
return self
def __repr__(self):
return "<cout>"
cout = PythonCout()
cout << "hello" << endl
But then trying to simulate cin:
class PythonCin:
def __rshift__(self, string):
string = sys.stdin.readline() # which doesn't make sense
line = ""
cin >> line
And there goes the need to modify a string. :)
More information about the Python-list
mailing list