简体   繁体   中英

Compare two Python strings with hyphen/dash

I am trying to compare to strings in Python and noticed that when a dash/hyphen is present in the string it will not equate identical strings. For example:

>>>teststring = 'newstring'
>>>teststring is 'newstring'
True

Then, if I add a dash

>>>teststring = 'new-string'
>>>teststring is 'new-string'
False

Why is that the case, and what would be the best way to compare strings with dashes?

you should never use is to compare equality anyway. is tests for identity. Use == .

Frankly I don't know why 'newstring' is 'newstring' . I'm sure it varies based on your Python implementation as it seems like a memory-saving cache to re-use short strings.

However:

teststring = 'newstring'
teststring == 'newstring' # True

nextstring = 'new-string'
nextstring == 'new-string' # True

basically all is does is test id s to make sure they're identical.

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.

You should not use is for string comparison. Is checks if both objects are same. You should use equality operator == here. That compares the values of objects, rather than ids of objects.

In this case, looks like Python is doing some object optimizations for string objects and hence the behavior.

>>> 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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM