Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/python/298.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
理解一种python数据类型存在问题_Python - Fatal编程技术网

理解一种python数据类型存在问题

理解一种python数据类型存在问题,python,Python,从这个代码中,你可以把字母h改成j,这意味着它是可变的 这意味着它是可变的 不,Python字符串是不可变的。str.replace和任何其他string方法返回一个新字符串 如果字符串是可变的,那么下面的代码 x = "hello, world" print(x.replace("h","j") 将输出jello,而不是它的世界。这并不意味着字符串是可变的,这意味着我们正在replace方法中创建一个新字符串 从字符串的id可以看出

从这个代码中,你可以把字母h改成j,这意味着它是可变的

这意味着它是可变的

不,Python字符串是不可变的。str.replace和任何其他string方法返回一个新字符串

如果字符串是可变的,那么下面的代码

x = "hello, world"
print(x.replace("h","j")

将输出jello,而不是它的世界。

这并不意味着字符串是可变的,这意味着我们正在replace方法中创建一个新字符串


从字符串的id可以看出,它们是两个不同的字符串。也可以使用is运算符进行比较。

字符串在python中是不可变的

>>> a= "ababa"
>>> id(a)
48421600L
>>> id(a.replace('a','c'))
48419776L
>>>
当您尝试修改字符串对象的值时,它会指向内存中具有不同位置的新字符串,因为字符串是不可变的。
idx返回x的内存地址。

在它们的生命周期中有唯一的,这就是这种比较的情况,所以我看不出问题所在。这是否回答了您的问题?
>>> a= "ababa"
>>> id(a)
48421600L
>>> id(a.replace('a','c'))
48419776L
>>>
>>> x = 'hello, world'
>>> x
[OUT]: 'hello, world'
>>> id(x)
[OUT]: 4400926320
>>> x = x.replace('h','j')
>>> x
[OUT]: 'jello, world'
>>> id(x)
[OUT]: 4402216304