coderunner007 coderunner007 - 1 month ago 9
Python Question

Python strings are said to be 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

Answer

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"