📜  Python|相同和不同的价值空间

📅  最后修改于: 2022-05-13 01:55:10.849000             🧑  作者: Mango

Python|相同和不同的价值空间

在Python中,即使它们共享不同的变量,我们对于相似的值也有相同的池。这有很多优点,它可以节省大量内存,为相似的值安排不同的空间。这是为小整数提供的。但是有一些方法可以让我们拥有相同和不同的池值。让我们讨论相同的某些情况。

案例 #1:同一个池(使用 +运算符)
在这种情况下,当我们使用“+”运算符创建一个字符串时,我们会创建一个指向内存中相似空间的空间。

# Python3 code to demonstrate working of 
# Same and Different value space
# Same value case
  
# initializing strings
test_str1 = "gfg"
  
# printing original string
print("The original string is : " + test_str1)
  
# Using + to construct second string 
test_str2 = "g" + "fg"
  
# testing values 
res = test_str1 is test_str2
  
# printing result 
print("Are values pointing to same pool ? : " + str(res)) 
输出 :
The original string is : gfg
Are values pointing to same pool ? : True

案例 #2:不同的池(使用join() + ord()
这是我们需要初始化指向内存中不同值空间的字符串的方式。这可以使用 join() 来连接使用 ord() 提取的 ASCII 值。

# Python3 code to demonstrate working of 
# Same and Different value space
# Different value case
  
# initializing strings
test_str1 = "abc"
  
# printing original string
print("The original string is : " + test_str1)
  
# Using join() + ord() to construct second string 
test_str2 = ''.join((chr(idx) for idx in range(97, 100)))
  
# testing values 
res = test_str1 is test_str2
  
# printing result 
print("Are values pointing to same pool ? : " + str(res)) 
输出 :
The original string is : abc
Are values pointing to same pool ? : False