Reputation: 68790
import string
print string.ascii_lowercase # abcdefghijklmnopqrstuvwxyz
print type(string.ascii_lowercase) # <type 'str'>
print string.ascii_lowercase is str # False
Shouldn't it be True
?
Upvotes: 3
Views: 421
Reputation: 125327
string.ascii_lowercase is str
should not be True
.
type(string.ascii_lowercase) is str
is True
.
The is
keyword checks object identity, not type.
You may have seen code like foo is None
often and thought that None
is a type. None
is actually a singleton object.
Upvotes: 2
Reputation: 320019
use:
>>> isinstance('dfab', str)
True
is
intended for identity testing.
Upvotes: 3
Reputation: 14669
The is
operator compares the identity of two objects. This is what I believe it does behind the scenes:
id(string.ascii_lowercase) == id(str)
Actual strings are always going to have a different identity than the type str
, so this will always be False
.
Here is the most Pythonic way to test whether something is a string:
isinstance(string.ascii_lowercase, basestring)
This will match both str
and unicode
strings.
Upvotes: 4