首先说两个运算符:
" == " 运算符测试值的等价性,递归地比较所有内嵌对象
" is " 表达式测试对象的同一性,测试两者是否为同一对象(是否为同一地址)
Python内部会对临时存储并重复使用的段字符串做优化,在PyCharm中优化的很好
下边是在PyCharm中运行的
s1 = ‘hello‘ s2 = ‘hello‘ print(s1 is s2) s1 = ‘hello world‘ s2 = ‘hello world‘ print(s1 is s2) s1 = ‘h e l l o‘ s2 = ‘h e l l o‘ print(s1 is s2) s1 = ‘a longer string‘ s2 = ‘a longer string‘ print(s1 is s2) s1 = ‘hello world good morning‘ s2 = ‘hello world good morning‘ print(s1 is s2)
True True True True True
下边是在Python交互器中运行的现象。
>>> s1 = "spam" >>> s2 = "spam" >>> s1 is s2 True >>> s1 = "sp am" >>> s2 = "sp am" >>> s1 is s2 False >>> s1 = ‘ ‘ >>> s2 = ‘ ‘ >>> s1 is s2 True >>> s1 = ‘ ‘ >>> s2 = ‘ ‘ >>> s1 is s2 False >>> s1 = ‘kkkkkkkkkkkkkkkkkkkkk‘ >>> s2 = ‘kkkkkkkkkkkkkkkkkkkkk‘ >>> s1 is s2 True >>> s1 = ‘\t\t‘ >>> s2 = ‘\t\t‘ >>> s1 is s2 False >>> s1 = ‘\n‘ >>> s2 = ‘\n‘ >>> s1 is s2 True
没试验太多数据,老哥们要是有新的发现也可以跟我说
原文地址:https://www.cnblogs.com/cong12586/p/10742490.html
时间: 2024-10-18 22:12:08