Tests whether an object is a class string

Source: Internet
Author: User

Sometimes you need to test an object, especially if you write a function or a method, you need to test whether the passed argument is a string (or if the object behaves like a string):

The following approach is to use the built-in isinstance and basestring to quickly and easily check whether an object is a string or Unicode object, as follows:

 

We might first reflect the type test using the Type method:

def isastring (anobj): return type (anobj) is type (") is not pythonic in this way, and Unicode objects cannot pass detection. 

The first detection method is much better, built into Basestring is the STR and Unicode type to the common base class, any class string custom type should be derived from basestring, so as to ensure that the isinstance work properly. However, the Isinstance method is not 100% perfect detection scheme, for the userstring module in the Python standard library to the UserString class to the instance, cannot pass the detection. The UserString object is an obvious class-string object because it is not derived from basestring. If you want to support this type of detection, you can directly check whether an object behaves like a string, for example:

def isstringlike (anobj): try: anobj+ ' Except:return False return True 

This method is much slower than the isastring function, but detection for userstring is also suitable for STR and Unicode.

Summary: The usual type checking method in Python is the so-called duck judgment: if it walks like a duck and cries like a duck, then for us it is a duck.

Tests whether an object is a class string

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.