How can I check if a Python object is a string (either regular or Unicode)?
Show activity on this post. if (obj instanceof String) { String str = (String) obj; // need to declare and cast again the object .. str. contains(..) .. }else{ str = .... }
Strings are objects in Python which means that there is a set of built-in functions that you can use to manipulate strings.
To get the type of a variable in Python, you can use the built-in type() function. In Python, everything is an object. So, when you use the type() function to print the type of the value stored in a variable to the console, it returns the class type of the object.
String find() in Python Just call the method on the string object to search for a string, like so: obj. find(“search”). The find() method searches for a query string and returns the character position if found. If the string is not found, it returns -1.
Use isinstance(obj, basestring) for an object-to-test obj.
Docs.
In Python 3.x basestring is not available anymore, as str is the sole string type (with the semantics of Python 2.x's unicode).
So the check in Python 3.x is just:
isinstance(obj_to_test, str) This follows the fix of the official 2to3 conversion tool: converting basestring to str.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With