简体   繁体   中英

If strings are immutable, then how is this possible?

I am new to python and was going through the python3 docs. In python strings are said to be immutable, then how is this possible:

if __name__ == '__main__':
        l = 'string'
        print(l)
        l = l[:2]
        print(l)

returns this output:

string
st

Informally, l now points to a new immutable string, which is a copy of a part of the old one.

What you cannot do is modify a string in place.

a = "hello"
a[0] = "b"  # not allowed to modify the string `a` is referencing; raises TypeError

print(a)  # not reached, since we got an exception at the previous line

but you can do this:

a = "hello"
a = "b" + a[1:]  # ok, since we're making a new copy

print(a)  # prints "bello"

The key to understanding this problem is to realize that the variable in Python is just a "pointer" pointing to an underlying object. And you confused the concept of immutable object and immutable variable(which does not exist in Python).

For instance, in your case, l was initially a pointer pointing to a str object with content "string". But later, you "redirect" it to a new str object whose content is "st". Note that when the program runs to the line l = l[:2] , it's the pointer being modified, not the object pointed to by the pointer. If you wish, you can also "redirect" l to another object with type other than str , say l = 123 . Just remember, the original object pointed to by l ( str "string") is not modified at all, it's still there in the memory (before it is garbage-collected), but just no longer pointed to by l .

For you to better understand the concept of immutable object, let's look at a mutable object. For example, list in Python is mutable.

l = [1, 2, 3] # a new list with three elements
l.append(4) # append a new element 4 to the list (l is now modified!!!)

In the code above, we modified l by appending a new element to it. Throughout the program, l points to the same object, but it's the object pointed to by l that is changed in the process.

Strings themselves are immutable, but the variables can be bound to anything. The id() method checks the "id" of an object. See below.

>>> l = 'string'
>>> print(l, id(l))
string 2257903593544
>>> l = l[:2]
>>> print(l, id(l))
st 2257912916040

l was bounded to a new immutable object which only contains "st".

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM