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'
l = l[:2]
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 = "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"