Skip to main content
 首页 » 编程设计

python之如果字符串是不可变的,那这怎么可能呢

2025年05月04日16zengkefu

我是 python 的新手,正在浏览 python3 文档。在 python 中,字符串被认为是不可变的,那么这怎么可能:

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

返回此输出:

string 
st 

请您参考如下方法:

非正式地,l 现在指向一个新的不可变字符串,它是旧字符串的一部分的副本。

您不能做的是就地修改字符串。

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 

但是你可以这样做:

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