[Python Wpg] Recipe of the day: testing if x is a string (including unicode)
Sydney Weidman
syd at plug.ca
Fri Aug 17 11:59:02 EDT 2007
This is probably something I should have learned long ago, but I was
flipping through the first few pages of the Python Cookbook and
discovered this:
isinstance(x, str)
is False for unicode strings. Hmmm... probably should have known that.
I could test for both str and unicode:
isinstance(x, str) or isinstance(x, unicode)
but that seems awfully clumsy and uncharacteristically verbose for
Python.
Apparently, someone has thought of this :-)
The correct test is:
isinstance(x, basestring)
[GCC 4.0.2 20051125 (Red Hat 4.0.2-8)] on linux2
Type "help", "copyright", "credits" or "license" for more information.
>>> x = u'\u2020'
>>> isinstance(x,str)
False
>>> isinstance(x,unicode)
True
>>> isinstance(x,basestring)
True
>>>
>>> isinstance('normal string', basestring)
True
>>>
Thanks to Luther Blissett for recipe 1.3 of the Python Cookbook
Hope everyone is having a great summer.
P.S. Any topic suggestions for the 4th Wednesday in September (the
26th)?
- Syd
More information about the Winnipeg
mailing list