Reputation: 11
If I have a string which is the same as a python data type and I would like to check if another variable is that type how would I do it? Example below.
dtype = 'str'
x = 'hello'
bool = type(x) == dtype
The above obviously returns False but I'd like to check that type('hello') is a string.
Upvotes: 1
Views: 1403
Reputation: 1
One solution is using .__name__
as follows:
dtype = 'str'
x = 'hello'
bool = type(x).__name__ == dtype
Upvotes: 0
Reputation: 218
bool = type(x) == dtype
because dtype
is a variabe It is in the form of a string , not logical !!
you should be entered a statement to check is str or no
Also, the string in Python is an object so to call it write :
str
not write dtype = 'str'
,exemple :
type(x) == str
x = 'hello'
if type(x) == str:
print(True)
else:
print(False)
It's a simple code but there are other shortcuts that come from Python
try that and good day for coding !!
Upvotes: 1
Reputation: 404
I think the best way to do this verification is to use isinstance, like:
isinstance(x, str) # returns True
From the docs:
isinstance(object, classinfo)
Return True if the object argument is an instance of the classinfo argument, or of a (direct, indirect or virtual) subclass thereof. If object is not an object of the given type, the function always returns False. If classinfo is a tuple of type objects (or recursively, other such tuples), return True if object is an instance of any of the types. If classinfo is not a type or tuple of types and such tuples, a TypeError exception is raised.
https://docs.python.org/3/library/functions.html#isinstance
Upvotes: 0
Reputation: 70267
If your code actually looks like the example you showed and dtype
isn't coming from user input, then also keep in mind that str
(as a value in Python) is a valid object which represents the string type. Consider
dtype = str
x = 'hello'
print(isinstance(x, dtype))
str
is a value like any other and can be assigned to variables. No eval
magic required.
Upvotes: 0
Reputation: 5560
You can use eval
:
bool = type(x) is eval(dtype)
but beware, eval
will execute any python code, so if you're taking dtype
as user input, they can execute their own code in this line.
Upvotes: 1