string type check in python - python

I'm trying to do a type check with an element of a pandas dataframe which appears to be a string:
type(atmdf.ix[row]['bid'])
<type 'str'>
however, if I do a type check I get False:
type(atmdf.ix[row]['bid']) is 'str'
False
even with the isinstance I get the same unexpected result:
isinstance(type(atmdf.ix[row]['bid']), str)
False
where am I wrong?
P.S. the content of the dataframe is something like this:
atmdf.ix[row]['bid']
'28.5'
thank you!

You have to test the string itself with isintance, not the type:
In [2]: isinstance('string', str)
Out[2]: True
So in your case (leaving out the type(..)): isinstance(atmdf.ix[row]['bid'], str).
Your first check did not work because you have to compare to str (the type) not 'str' (a string).

Related

How to check if some datatype is string or list in python?

I'm trying to add a check here that if the receiver is just a string. then convert that into list else just pass.
if type(receiver) == str:
receiver=[receiver]
error:
TypeError: 'str' object is not callable
You can check the type of an instance with the following.
if isinstance(receiver, str):
# do something if it is a string
If you just need to check rather it is not a string:
if not isinstance(receiver, str):
# do something if it is not a string
Look at this tutorial to learn more about the function.
a = '123'
print(str(a))
print(type(a))

hamcrest: how to input Boolean value

I am not sure why I see error when I have this code. all_is_valid is highlighted in yellow and when I hover over I see below error message. How do I avoid not highlighting it?
Expected type 'Matcher[bool]' (matched generic type 'Matcher[T]'), got 'bool' instead
all_is_valid=True
actual = None
if not actual:
all_is_valid = False
assert_that(True, all_is_valid,"test failed")
Trying to convert your input to bool won't work like that. Python considers any non-empty string True. So doing bool(input()) is basically the same as doing input() != ''. Both return true even if the input wasn't "True". Just compare the input given directly to the strings "True and "False":`isTrue = True
while isTrue:
isTrue = bool(int(input("Continue? 1 for yes, 0 for no: ")))`

Why isn't type(string) equal to "<class 'str'>"?

In Python 3 type('jjj')=="<class 'str'>", it evaluates to False, while in Python 2 type('jjj')=="<type 'str'>" has the same results. Don't know why is this happening, so any help (even a little push) is appreciated!
That's because the type function doesn't return a string. It returns a type 'type':
>>> type(type('hi'))
<type 'type'>
So what you're doing at the moment is comparing a type 'type' to a type 'string', which will have the result False.
I recommend using isinstance:
>>> isinstance('hi', str)
True
Confusion can be induced by shells. Some displays the type name when other print the representation of the type.
As an illustration
python shell
>>>type('jj')
<class 'str'>
Ipython
In [68]: type('a')
Out[68]: str
Here the two string used:
In [69]: str.__name__
Out[69]: 'str'
In [70]: repr(str)
Out[70]: "<class 'str'>"
As said isinstance is the good way to test a type.

Decide value from django template 'int' or 'str'

I have a form in django template. In the view that gets data from this form, I need to check if the entry is 'str' or 'int'. If it's 'str', I have to raise an error. But when I check the type of the entry by using:
pr = request.GET['pr no']
print "Type of PR:%s" % type(pr)
irrespective of the 'pr' being string or integer, type() function returns 'unicode'. How do I go about it?
Thanks
Well, obviously .GET['pr no'] always returns a Unicode object then.
Whether that string contains an integer can be tested:
if pr.isdigit(): # ASCII digits
or
if pr.isnumeric(): # also Unicode digits
Alternatively, you could do
try:
int(pr)
except ValueError:
print "PR is not an integer"
or check for any valid number:
try:
float(pr)
except ValueError:
print "PR is not a number"
In html form, text input box is used to input integer values. So values you get in python view for it will always be unicode string.
To achieve what you want to do, you can test with .isdigit() method of unicode string.
Example:
>>> x=u'99A'
>>> x.isdigit()
False
>>> x=u'99'
>>> x.isdigit()
True
>>>
>>> x=u'A99'
>>> x.isdigit()
False
>>>
If you are using django form, you may want to use appropriate form field (likely IntegerField ) and validate the form to get errors.

Break statement in Python

I am trying to break out of a for loop, but for some reason the following doesn't work as expected:
for out in dbOutPut:
case_id = out['case_id']
string = out['subject']
vectorspace = create_vector_space_model(case_id, string, tfidf_dict)
vectorspace_list.append(vectorspace)
case_id_list.append(case_id)
print len(case_id_list)
if len(case_id_list) >= kcount:
print "true"
break
It just keeps iterating untill the end of dbOutput. What am I doing wrong?
I'm guessing, based on your previous question, that kcount is a string, not an int. Note that when you compare an int with a string, (in CPython version 2) the int is always less than the string because 'int' comes before 'str' in alphabetic order:
In [12]: 100 >= '2'
Out[12]: False
If kcount is a string, then the solution is add a type to the argparse argument:
import argparse
parser=argparse.ArgumentParser()
parser.add_argument('-k', type = int, help = 'number of clusters')
args=parser.parse_args()
print(type(args.k))
print(args.k)
running
% test.py -k 2
yields
<type 'int'>
2
This confusing error would not arise in Python3. There, comparing an int and a str raises a TypeError.
Could it happen that kcount is actually a string, not an integer and, therefore, could never become less than any integer?
See string to int comparison in python question for more details.

Categories