osdir.com


[Date Prev][Date Next][Thread Prev][Thread Next][Date Index][Thread Index]

The use of type()


Follow on to below. I was right and there is a fairly trivial and portable
way to just show 'int' for the type of probably many types:

No need to call the type() function at all.

If "a" is an integer object containing "5" then you can ask for the class of
it and then within that for the name like this:

>>> a = 5
>>> print(a.__class__.__name__)
int
>>> b = 5.0
>>> print(b.__class__.__name__)
float

-----Original Message-----
From: Python-list <python-list-bounces+avigross=verizon.net at python.org> On
Behalf Of Avi Gross
Sent: Sunday, February 10, 2019 5:43 PM
To: python-list at python.org
Subject: RE: The use of type()

Without using regular expressions, if you just want to extract the word
"int" or "float" you can substring the results by converting what type says
to a string:

>>> a = 5
>>> str(type(a))[8:11]
'int'

>>> a=5.0
>>> str(type(a))[8:13]
'float'

Since the format and length vary, this may not meet your needs. You could
search for the first index where there is a single quote and then the next
and take what is in between.

You can run this in-line or make a function that might work for at least the
basic types:

>>> a = 5
>>> text = str(type(a))
>>> first = text.find("'")
>>> first += 1
>>> second = text.find("'", first)
>>> first, second
(8, 11)
>>> text[first : second]
'int'
>>> print(text[first : second])
Int

If I do the same with a float like 5.0:

>>> a=5.0
>>> text = str(type(a))
>>> first = text.find("'")
>>> first += 1
>>> second = text.find("'", first)
>>> print(text[first : second])
float

For a list:

>>> a = ["list", "of", "anything"]
..
>>> print(text[first : second])
list

Of course this is so simple it must be out there in some module.




-----Original Message-----
From: Python-list <python-list-bounces+avigross=verizon.net at python.org> On
Behalf Of ^Bart
Sent: Sunday, February 10, 2019 4:43 PM
To: python-list at python.org
Subject: The use of type()

I need to print something like "this variable is int" or "this variable is
string"

n1 = 10
n2 = 23

print ("Total of n1+n2 is: ",n1+n2," the type is", type(n1+n2))

When I run it I have:

Total of n1+n2 is:  33  the type is <class 'int'>  >>>

I'd like to read "the type is int" and NOT "the type is <class 'int'>, how
could I solve it?

^Bart
--
https://mail.python.org/mailman/listinfo/python-list

--
https://mail.python.org/mailman/listinfo/python-list