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

1
  • Which version of Python? Commented Jan 17, 2010 at 15:03

4 Answers 4

4

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.

Sign up to request clarification or add additional context in comments.

1 Comment

Thanks for the id() example, got it now! :)
3

use:

>>> isinstance('dfab', str)
True

is intended for identity testing.

1 Comment

+1 docs.python.org/library/… "Return true if the object argument is an instance of the classinfo argument, or of a (direct or indirect) subclass thereof."
2

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.

4 Comments

Oh, why not? any technical reason that I must know?
because string.ascii_lowercase is a string, whereas str is a type.
is test's whether they are the same object. i.e. they are both pointers to an object, are those objects the same.
See what happens when you do type(str)
0

Don't you want type(string.ascii_lowercase) is str ?

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.