Identify whether the value being printed is of type float, string or int

3

In python it is possible to print various types of variables using print . Here's an example:

print(3.4, "hello", 45);

Or individually.

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

How can you identify whether the value being printed is float , string or int ?

    
asked by anonymous 23.03.2017 / 17:00

2 answers

4

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 float , str , int you can:

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

For verifications you can use and is more straightforward isinstance (var, (objs,)) :

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

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

if isinstance(3.4, (float, str)):
    # True, e float ou string
    
23.03.2017 / 17:04
2

Use the type

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

>> <class 'float'> <class 'str'> <class 'int'>
    
23.03.2017 / 17:05