使用连字符/破折号比较两个Python字符串
我试图与Python中的字符串进行比较,并注意到当字符串中出现破折号/连字符时,它不会等同于相同的字符串。例如:使用连字符/破折号比较两个Python字符串,python,string,python-2.7,special-characters,Python,String,Python 2.7,Special Characters,我试图与Python中的字符串进行比较,并注意到当字符串中出现破折号/连字符时,它不会等同于相同的字符串。例如: >>>teststring = 'newstring' >>>teststring is 'newstring' True 那么,如果我加一个破折号 >>>teststring = 'new-string' >>>teststring is 'new-string' False 为什么会出现这种情况,比较字符
>>>teststring = 'newstring'
>>>teststring is 'newstring'
True
那么,如果我加一个破折号
>>>teststring = 'new-string'
>>>teststring is 'new-string'
False
为什么会出现这种情况,比较字符串和破折号的最佳方法是什么?无论如何,您都不应该使用
is
来比较相等性<代码>is测试身份。使用==
坦白地说,我不知道为什么“newstring”是“newstring”。我相信它会根据您的Python实现而有所不同,因为它看起来像是一个节省内存的缓存,可以重复使用短字符串
然而:
teststring = 'newstring'
teststring == 'newstring' # True
nextstring = 'new-string'
nextstring == 'new-string' # True
基本上,is
所做的就是测试id
s以确保它们是相同的
id('new-string') # 48441808
id('new-string') # 48435352
# These change
id('newstring') # 48441728
id('newstring') # 48441728
# These don't, and I don't know why.
不应使用
is
进行字符串比较。Is检查两个对象是否相同。您应该在此处使用相等运算符==
。它比较对象的值,而不是对象的ID
在本例中,Python似乎正在对字符串对象进行一些对象优化,从而实现行为优化
>>> teststring = 'newstring'
>>> id(teststring)
4329009776
>>> id('newstring')
4329009776
>>> teststring = 'new-string'
>>> id(teststring)
4329009840
>>> id('new-string')
4329009776
>>> teststring == 'new-string'
True
>>> teststring is 'new-string'
False
请参阅,了解为什么
is
有时会起作用。从我的答案来看:[T]Python编译器还将插入任何作为常量存储的Python字符串,只要它是有效的标识符。Python代码对象工厂函数PyCode_New将插入任何只包含字母、数字或下划线的字符串对象。下面是对默认设置的get的更深入研究:测试是否相等,而不是标识。使用=
。请参阅关于Python何时实习字符串(以及身份测试工作)。这很有意义。因此,这与python处理0-255个整型对象类似,整型对象始终存在于内存中。Python从不为这些int创建新对象,只是在需要时添加ref计数。但是,这是一个实现细节,而不是代码应该依赖的东西。