Hi,
How can i create a ref to a string ? it doesn't work like lists :S

List : (IDs are the same!)

>>> li=[1, 2, 3, 4, 5]
>>> li_ref=li
>>> id(li)
13545800
>>> id(li_ref)
13545800
>>> li.pop()
5
>>> li
[1, 2, 3, 4]
>>> id(li)
13545800
>>> li_ref
[1, 2, 3, 4]
>>> id(li_ref)
13545800

String : (the ID of each is different!)

>>> s="Hello, "
>>> s_ref=s
>>> id(s)
13553952
>>> id(s_ref)
13553952
>>> s += "World!"
>>> s
'Hello, World!'
>>> s_ref
'Hello, '
>>> id(s)
13560752
>>> id(s_ref)
13553952

So any ideas ?

>>> a=b="test"
>>> print a
test
>>> print b
test
>>> id(a)
3084724384L
>>> id(b)
3084724384L

Or convert the string to a list and then back to a string when you are finished.

Strings are known as immutable. You cannot take a string object and change its value without creating another string, so although you can have two names refer to the same string object, when you create a new string object and assign it to one of the names, the other name is still referring to the original object.

You could embed a string in a list and have two names refer to the list. Then changing the string in the list will be seen via both names
i.e:

s1 = ["Spam"]
s2 = s1
s2[0] = "Ham"
assert s1 == ["Ham"]

- Paddy.

or create a class that looks like a string:

class MyString(object):

    def __init__(self, string):
        self.value = string

    def __str__(self):
        return self.value

    # I think strings ought to support index assignment.  So my strings will.
    def __setitem__(self, index, item):
        self.value = self.value[:index] + item + self.value[index+1:]

    def __getitem__(self, index):
        return self.value[index]

    def __mul__(self, multiple):
        return self.value * multiple

    def __add__(self, addend):
        return self.value + addend

    def __iadd__(self, addend):
        self.value += addend
        return self
  
   # add more methods to make it even more string-like.

a = MyString("Hi!")
print a, id(a)
print a*5, id(a)
a += "whoa!"
print a, id(a)
print a[1], id(a)
a[2] = "?"
print a, id(a)

---
Hi! 12077744
Hi!Hi!Hi!Hi!Hi! 12077744
Hi!whoa! 12077744
i 12077744
Hi?whoa! 12077744

But now this raises the question: why do you want such a thing?

Jeff

Check out the mutable string class past the middle of this page

Sorry for being late,
Thanks guyz, that was helpful

Ooh, the MutableString class was interesting. Thanks, paddy. Of course, the various caveats on that page were not very encouraging...:D

Jeff

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.