Identify if the value being printed is float, string or int

Asked

Viewed 327 times

3

In python it is possible to make an impression of several types of variables using the print. Take an example:

print(3.4, "hello", 45);

Or individually.

print(3.4);
print("hello");
print(45);

How is it possible to identify if the value being printed is of the type float, string or int?

2 answers

5


To know the type/class we can do (type):

print(type(3.4), type("hello"), type(45)) # <class 'float'> <class 'str'> <class 'int'>

To filter only the part of the float, str, int can:

print(type(3.4).__name__, type("hello").__name__, type(45).__name__) # float str int

For checks can use and is more direct isinstance(var, (objs,)):

if isinstance(3.4, float):
    # True, e float

You can even check if it belongs to one of several types/classes that enter as argument within a tuple:

if isinstance(3.4, (float, str)):
    # True, e float ou string

2

Use the function type

print(type(3.4), type("hello"), type(45))

>> <class 'float'> <class 'str'> <class 'int'>

Browser other questions tagged

You are not signed in. Login or sign up in order to post.