Python print data type

Get and check the type of an object in Python: type(), isinstance()

In Python, you can get, print, and check the type of an object (variable and literal) with the built-in type() and isinstance() functions.

Instead of checking the type of an object, you can handle exceptions or use the built-in hasattr() function to determine whether an object has the correct methods and attributes. For more information, see the following article.

See the following article for information on how to determine class inheritance relationships and obtain a list of subclasses and superclasses.

Get and print the type of an object: type()

type() returns the type of an object. It can be used to get and print the type of a variable or a literal, similar to typeof in other programming languages.

print(type('string')) # print(type(100)) # print(type([0, 1, 2])) # 

The return value of type() is a type object such as str or int .

print(type(type('string'))) # print(type(str)) # 

Check the type of an object: type() , isinstance()

Use type() or isinstance() to check whether an object is of a specific type.

With type()

By comparing the return value of type() with a specific type, you can check whether the object is of that type.

print(type('string') is str) # True print(type('string') is int) # False 
def is_str(v): return type(v) is str print(is_str('string')) # True print(is_str(100)) # False print(is_str([0, 1, 2])) # False 

To check if an object is one of several types, use the in keyword combined with a tuple containing multiple types.

def is_str_or_int(v): return type(v) in (str, int) print(is_str_or_int('string')) # True print(is_str_or_int(100)) # True print(is_str_or_int([0, 1, 2])) # False 

You can also define functions that modify their behavior based on the input type.

def type_condition(v): if type(v) is str: print('type is str') elif type(v) is int: print('type is int') else: print('type is not str or int') type_condition('string') # type is str type_condition(100) # type is int type_condition([0, 1, 2]) # type is not str or int 

With isinstance()

isinstance(object, type) returns True if the object argument is an instance of the specified type argument or an instance of a subclass derived from that type .

You can use a tuple as the second argument to check for multiple types. It returns True if the object is an instance of any of the specified types.

print(isinstance('string', str)) # True print(isinstance(100, str)) # False print(isinstance(100, (int, str))) # True 

Functions similar to the above examples using type() can be implemented as follows:

def is_str(v): return isinstance(v, str) print(is_str('string')) # True print(is_str(100)) # False print(is_str([0, 1, 2])) # False 
def is_str_or_int(v): return isinstance(v, (int, str)) print(is_str_or_int('string')) # True print(is_str_or_int(100)) # True print(is_str_or_int([0, 1, 2])) # False 
def type_condition(v): if isinstance(v, str): print('type is str') elif isinstance(v, int): print('type is int') else: print('type is not str or int') type_condition('string') # type is str type_condition(100) # type is int type_condition([0, 1, 2]) # type is not str or int 

The difference between type() and isinstance()

The key difference between type() and isinstance() lies in their treatment of inheritance: isinstance() returns True for instances of subclasses inheriting from the specified class, while type() returns True only for exact type matches.

For example, define the following superclass (base class) and subclass (derived class).

class Base: pass class Derive(Base): pass base = Base() print(type(base)) # derive = Derive() print(type(derive)) # 

type() returns True only when the types match, but isinstance() returns True also for the superclass.

print(type(derive) is Derive) # True print(type(derive) is Base) # False print(isinstance(derive, Derive)) # True print(isinstance(derive, Base)) # True 

As another example, bool ( True and False ) is a subclass of int . Thus, in isinstance() , a bool object returns True for both int and bool .

print(type(True)) # print(type(True) is bool) # True print(type(True) is int) # False print(isinstance(True, bool)) # True print(isinstance(True, int)) # True 

Use type() to check the exact type of an object, and isinstance() to check the type while considering inheritance.

The built-in issubclass() function can be used to check whether a class is a subclass of another class.

print(issubclass(bool, int)) # True print(issubclass(bool, float)) # False 

Источник

Python Print Type of Variable – How to Get Var Type

Kolade Chris

Kolade Chris

Python Print Type of Variable – How to Get Var Type

If you’re a Python beginner, becoming familiar with all its various data types can be confusing at first. After all, there are a lot of them available to you in the language.

In this article, I’m going to show you how to get the type of various data structures in Python by assigning them to a variable, and then printing the type to the console with the print() function.

How to Print the Type of a Variable in Python

To get the type of a variable in Python, you can use the built-in type() function.

The basic syntax looks like this:

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.

For instance, if the type is a string and you use the type() on it, you’d get as the result.

To show you the type() function in action, I’m going to declare some variables and assign to them the various data types in Python.

name = "freeCodeCamp" score = 99.99 lessons = ["RWD", "JavaScript", "Databases", "Python"] person = < "firstName": "John", "lastName": "Doe", "age": 28 >langs = ("Python", "JavaScript", "Golang") basics =

I will then print the types to the console by wrapping print() around some strings and the type() function.

print("The variable, name is of type:", type(name)) print("The variable, score is of type:", type(score)) print("The variable, lessons is of type:", type(lessons)) print("The variable, person is of type:", type(person)) print("The variable, langs is of type:", type(langs)) print("The variable, basics is of type:", type(basics)) 

Here are the outputs:

# Outputs: # The variable, name is of type: # The variable, score is of type: # The variable, lessons is of type: # The variable, person is of type: # The variable, langs is of type: # The variable, basics is of type:

Final Thoughts

The type() function is a valuable built-in function of Python with which you can get the data type of a variable.

If you’re a beginner, you should save yourself the hassle of cramming data types by using the type() function to print the type of a variable to the console. This will save you some time.

You can also use the type() function for debugging because in Python, variables are not declared with data types. So, the type() function was built into the language for you to check for data types of variables.

Источник

Как узнать и вывести тип переменной в Python

Чтобы узнать и вывести тип переменной в Python, вы можете использовать type() вместе с функцией print(). Например, print(type(«ABC»)) возвращает . Функция type() возвращает тип данных переменной.

Синтаксис

Параметры

Функция возвращает свой тип, если единственный объект передается в type().

Пример

Давайте напечатаем различные типы переменных.

Вы можете видеть, что мы напечатали разные типы данных разных переменных.

Использование метода isinstance()

isinstance() — это встроенный метод Python, который возвращает True, если указанный объект имеет указанный тип. Метод isinstance() принимает два аргумента: объект и тип класса и возвращает значение True, если определенный объект имеет определенный тип.

Синтаксис

Аргументы

  1. object: это объект, экземпляр которого вы сравниваете с типом класса. Он вернет True, если тип соответствует; иначе false.
  2. class type: это тип, класс или кортеж типов и классов.

Пример

В этом примере мы будем сравнивать значение float с типом float, т. е. значение 19.21 будет сравниваться с типом float.

Используя метод isinstance(), вы можете проверить строку, число с плавающей запятой, целое число, список, кортеж, словарь, набор и класс.

Не используйте __class__

В Python имена, начинающиеся с подчеркивания, семантически не являются частью общедоступного API. Поэтому пользователям следует избегать их использования, за исключением случаев, когда это необходимо.

Источник

Python Print Type of Variable – How to Get Variable Type

To print a type of variable in Python, you can use the “type()” along with the “print()” function. For example, print(type(“ABC”)) returns . The type() function returns the variable’s data type.

Syntax

Parameters

The function returns its type if the single object is passed to type().

Example

Let’s print the different types of variables.

str = "Welcome to Guru99" run = 100 rr = 7.7 complex_num = 19j+21 player_list = ["VK", "RS", "JB", "RP"] bat_name = ("A", "B", "C", "D") duckworth = lbw = print("The type is : ", type(str)) print("The type is : ", type(run)) print("The type is : ", type(rr)) print("The type is : ", type(complex_num)) print("The type is : ", type(player_list)) print("The type is : ", type(bat_name)) print("The type is : ", type(duckworth)) print("The type is : ", type(lbw))
The type is : The type is : The type is : The type is : The type is : The type is : The type is : The type is : 

You can see that we printed the different data types of different variables.

Using isinstance() method

The isinstance() is a built-in Python method that returns True if a specified object is of the specified type. The isinstance() method accepts two arguments: object and classtype and returns True if the defined object is of the defined type.

Syntax

isinstance(object, classtype)

Arguments

object: It is an object whose instance you compare with class type. It will return True if the type matches; otherwise false.

class type: It is a type, class, or a tuple of types and classes.

Example

In this example, we will compare the float value with type float, i.e., the 19.21 value will be compared with type float.

fvalue = 19.21 dt = isinstance(fvalue, float) print("It is a float value:", dt)

And it returns True.

Using the isinstance() method, you can test for string, float, int, list, tuple, dict, set, and class.

How to print two variables in Python

To print the two variables in Python, use the print() function. The “%s” in print(“%s”) represents a String or any object with a string representation, like numbers.

name = "Stranger Things" season = 5 print("Total seasons for %s is %s" % (name, season))
Total seasons for Stranger Things are 5

2 thoughts on “Python Print Type of Variable – How to Get Variable Type”

Hi,
I just started to learn Python.
I have variables:
x=1j
y=2.2
Now, I would like to print them in a single print statement on two-line output, to show something like this:
X = 1j , , with comment1
Y = 2.3, , with comment2
Your advice would be greatly appreciated.
Cheers,
Zoltan. Reply

In the printout I would like to show the type() of the given variable as well. (I wrote it but
only two commas appeared instead.) Reply

Leave a Comment Cancel reply

This site uses Akismet to reduce spam. Learn how your comment data is processed.

Источник

Читайте также:  Html onclick return confirm
Оцените статью