Python:某个字符串[0:3]的类型是什么?

2024-10-03 11:26:31 发布

您现在位置:Python中文网/ 问答频道 /正文

我有以下python代码来进行字符串比较:

>>> mf="moo foo"

>>> mf[0:3]
'moo'

>>> mf[0:3] is "moo"
False

>>> mf[0:3] == "moo"
True

>>> str(mf[0:3]) is "moo"
False

所以double equals操作符返回true,但是pythonis操作符返回false。这一定是因为它们不是同一个对象。你知道吗

str[n:m]获得的字符序列和同一字符串的文字表示('moofoo')之间有什么技术区别?为什么它们不是同一个物体?你知道吗


Tags: 对象字符串代码falsetruefooisdouble
1条回答
网友
1楼 · 发布于 2024-10-03 11:26:31

is测试相等性以及相同的对象ID(在CPython中,这是内存中对象的地址)。str(...)而切片创建了一个浅拷贝,因此is测试失败。你知道吗

==测试相等的值。is测试对象标识。你知道吗

引自Python's Mailing List

'is' allows us to make the distinction if the system is keeping track of two things that just look alike, or are actually the same thing.

相关问题 更多 >