Reputation: 933
I wish to use a type function in an eval statement, so I need just the string representation of that function. For example:
print(type("cow"))
<class 'str'>
Here I need it to output 'str'. But when I try:
type("cow").__str__()
TypeError: descriptor '__str__' of 'str' object needs an argument
type("cow").__repr__()
TypeError: descriptor '__repr__' of 'str' object needs an argument
Curiously, Jupyter notebook prints it correctly if that is the last line in the cell.
Why is this error happening? What is the correct way to obtain just the Type string?
Upvotes: 1
Views: 771
Reputation: 41116
Given the question ambiguity, print(type("cow"))
is kind of misleading. Is cow:
Anyway here's a way that works for both:
>>> cow = "Moo!!" >>> >>> # Variable ... >>> cow.__class__.__name__ 'str' >>> # String literal ... >>> "cow".__class__.__name__ 'str'
For more details, check [Python 3.Docs]: Built-in Types - Special Attributes.
Upvotes: 2