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

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.

Related

Python pandas shows all ints in csv as floats

I want to verify that values in a CSV are integers and report an error if they are not. Being an amateur, I thought I had it figured out if the user entered '8k' or whatever as a value by using this:
try:
int(value)
except ValueError:
print("No Deal, Howie!")
I completely overlooked the possibility that a user can enter 8.8, which is unacceptable as well. Unfortunately, I can't use:
if type(value) == int
because pandas dataframe turns all the ints in my CSV into numpy.float64. What can I do about this?
Here's a pretty safe method that will capture a bunch of different integer types.
import numpy as np
def num_is_int(x):
if isinstance(x, (int, np.integer)):
return True
else:
try:
return x.is_integer()
except AttributeError:
return False
num_is_int(7)
True
num_is_int(7.0)
True
num_is_int(np.int16(7))
True
num_is_int(7.1)
False
num_is_int('7')
False
num_is_int(None)
False
You can use int() like this:
if value == int(value)
To check if the value is an integer you can convert it into a string, use .split() method and search for zeros.
An example:
A=5.000006
print(A)
B=str(A).split(sep='.')
print(B)
print(B[1])
integer=1
for b in B[1]:#B[1] is the decimal part of A
if b!='0':
integer=0
If integer=0, this is not an integer,
If integer=1 this is an integer.
I would use Python's builtin isinstance function. Like this:
if not isinstance(value, int):
print("No Deal, Howie!")

How to automatically determine type for user input?

I want to make a simple math function that takes user input, yet allows the user to not input an integer/float. I quickly learned Python does not identify type by default. Quick Google search shows using literal_eval, but it returns with ValueError: malformed string if a string is the input. This is what I have so far:
from ast import literal_eval
def distance_from_zero(x):
if type(x) == int or type(x) == float:
return abs(x)
else:
return "Not possible"
x = literal_eval(raw_input("Please try to enter a number "))
print distance_from_zero(x)
Just answer your query why ValueError: malformed string occurred if you read the literal_eval doc :
Safely evaluate an expression node or a string containing a Python
expression. The string or node provided may only consist of the
following Python literal structures: strings, numbers, tuples, lists,
dicts, booleans, and None.
so string should be inclosed by "" as used to write in editor like s = "string"
raw_input takes the input and convert to string data type so i have tried this and able to convert using literal_eval
>>> x=raw_input()
string
>>> x= "\""+x+"\"" # concatenating the "" to string
>>> literal_eval(x)
'string'
>>>
Like you mentioned you will get malformed string error (ValueError) if you get input like ast.literal_eval('c1'). You will also get SyntaxError if you do something like ast.literal_eval('1c'). You will want get the input data and then pass it to literal_eval. You can then catch both of these exceptions, and then return your 'Not Possible'.
from ast import literal_eval
def distance_from_zero(x):
try:
return abs(literal_eval(x))
except (SyntaxError, ValueError):
return 'Not possible'
x = raw_input("Please try to enter a number ")
print distance_from_zero(x)

Conversion From String To Int

I'm communicating with a modem via COM port to recieve CSQ values.
response = ser.readline()
csq = response[6:8]
print type(csq)
returns the following:
<type 'str'> and csq is a string with a value from 10-20
For further calculation I try to convert "csq" into an integer, but
i=int(csq)
returns following error:
invalid literal for int() with base 10: ''
A slightly more pythonic way:
i = int(csq) if csq else None
Your error message shows that you are trying to convert an empty string into an int which would cause problems.
Wrap your code in an if statement to check for empty strings:
if csq:
i = int(csq)
else:
i = None
Note that empty objects (empty lists, tuples, sets, strings etc) evaluate to False in Python.
As alternative you can put your code inside an try-except-block:
try:
i = int(csq)
except:
# some magic e.g.
i = False

AttributeError: 'str' object has no attribute 'isstr'

I am trying to make python module for jenni/phenny irc bot.
This is part of my code
def bp(jenni, input):
try:
text = input.group(2).encode('utf-8').split()
except:
jenni.reply("Please use correct syntax '.bp id weapons 7'. Available for weapons and food only")
if text[0].isstr() and text[1].isstr() and text[2].isdigit() and len(text) == 3 and text[1] == ('weapons' or 'food'):
url = 'http://someAPIurl/%s/%s/%s/1.xml?key=%s' % (text[0], text[1], text[2], key)
If the input is already a str why would I be getting this error?
AttributeError: 'str' object has no attribute 'isstr'
The error is exactly what it says; str has no method isstr().
If you want to make sure that it's only letter(s), use .isalpha().
Example:
>>> '0'.isalpha()
False
>>> 'a'.isalpha()
True
>>> 'aa'.isalpha()
True
Use isinstance and either basestring for Python 2.x and str or unicode for Python 3.x:
isinstance(your_string, basestring)
That is the question that you originally asked but is probably not what you meant. Your sample code suggests that you really want to know how to check to see if a string is either alphabetic or alphanumeric. For that you want to use the isalpha or isalnum string methods.
str.isalpha()
Return true if all characters in the string are
alphabetic and there is at least one character, false otherwise.
For 8-bit strings, this method is locale-dependent.
You may also want to consider refactoring your code to make it a bit easier to read and maintain. Maybe something like this:
API_URL = 'http://someAPIurl/%s/%s/%s/1.xml?key=%s'
KIND_CHOICES = ('weapon', 'food')
def bp(jenni, input):
try:
cmd, kind, index = input.group(2).encode('utf-8').split()
# Assigning to 3 variables lets you skip the len() == 3 check
# and can make the use of each argument more obvious than text[1]
except:
jenni.reply("Please use correct syntax '.bp id weapons 7'. Available for weapons and food only")
if cmd.isalpha() and kind in KIND_CHOICES and index.isdigit():
url = API_URL % (cmd, kind, index, key) # is key a global?
# ...
Try using: - text[0].isalpha()..
There is no such method isstr() for string..
And in place of text[1] == ('weapons' or 'food'), you should use in operator..
if (text[1] in ('weapons', 'food')) {
}

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