Python中字符串二三事
Posted 月为暮
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了Python中字符串二三事相关的知识,希望对你有一定的参考价值。
首先说两个运算符:
" == " 运算符测试值的等价性,递归地比较所有内嵌对象
" 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 = ‘ ‘ >>> s2 = ‘ ‘ >>> s1 is s2 False >>> s1 = ‘ ‘ >>> s2 = ‘ ‘ >>> s1 is s2 True
没试验太多数据,老哥们要是有新的发现也可以跟我说
以上是关于Python中字符串二三事的主要内容,如果未能解决你的问题,请参考以下文章