Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to check if type of a variable is string?

Is there a way to check if the type of a variable in python is a string, like:

isinstance(x,int); 

for integer values?

like image 819
c_pleaseUpvote Avatar asked Jan 30 '11 13:01

c_pleaseUpvote


People also ask

How do you check if a variable is a string or int?

The most efficient way to check if a string is an integer in Python is to use the str. isdigit() method, as it takes the least time to execute. The str. isdigit() method returns True if the string represents an integer, otherwise False .

How do you check if a variable is a string in Python?

Method #1 : Using isinstance(x, str) This method can be used to test whether any variable is a particular datatype. By giving the second argument as “str”, we can check if the variable we pass is a string or not.

How do you check if a variable is a type?

The typeof operator is used to obtain the System. Type object for a type. It is often used as a parameter or as a variable or field. It is used to perform a compile time lookup i.e. given a symbol representing a Class name, retrieve the Type object for it.

Is string type of a variable?

The two common types of variables that you are likely to see are numeric and string.


1 Answers

In Python 2.x, you would do

isinstance(s, basestring) 

basestring is the abstract superclass of str and unicode. It can be used to test whether an object is an instance of str or unicode.


In Python 3.x, the correct test is

isinstance(s, str) 

The bytes class isn't considered a string type in Python 3.

like image 182
Sven Marnach Avatar answered Oct 01 '22 09:10

Sven Marnach