Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to find out if a Python object is a string?

How can I check if a Python object is a string (either regular or Unicode)?

like image 459
Matt S. Avatar asked Aug 19 '09 23:08

Matt S.


People also ask

How do you know if an object is a string?

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 = .... }

Is object same as string Python?

Strings are objects in Python which means that there is a set of built-in functions that you can use to manipulate strings.

How do you check the type of an object in Python?

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.

How do you search for an object in a string in Python?

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.


2 Answers

Python 2

Use isinstance(obj, basestring) for an object-to-test obj.

Docs.

like image 143
John Fouhy Avatar answered Oct 04 '22 16:10

John Fouhy


Python 3

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.

like image 45
sevenforce Avatar answered Oct 04 '22 17:10

sevenforce