Conversion From String To Int - python

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

Related

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)

Python - AttributeError: 'str' object has no attribute 'append'

I keep receiving this error when I try to run this code for the line "encoded.append("i")":
AttributeError: 'str' object has no attribute 'append'
I cannot work out why the list won't append with the string. I'm sure the problem is very simple Thank you for your help.
def encode(code, msg):
'''Encrypts a message, msg, using the substitutions defined in the
dictionary, code'''
msg = list(msg)
encoded = []
for i in msg:
if i in code.keys():
i = code[i]
encoded.append(i)
else:
encoded.append(i)
encoded = ''.join(encoded)
return encoded
You set encoded to string here:
encoded = ''.join(encoded)
And of course it doesn't have attribute 'append'.
Since you're doing it on one of cycle iteration, on next iteration you have str instead of list...
>>> encoded =["d","4"]
>>> encoded="".join(encoded)
>>> print (type(encoded))
<class 'str'> #It's not a list anymore, you converted it to string.
>>> encoded =["d","4",4] # 4 here as integer
>>> encoded="".join(encoded)
Traceback (most recent call last):
File "<pyshell#4>", line 1, in <module>
encoded="".join(encoded)
TypeError: sequence item 2: expected str instance, int found
>>>
As you see, your list is converted to a string in here "".join(encoded). And append is a method of lists, not strings. That's why you got that error. Also as you see if your encoded list has an element as integer, you will see TypeError because, you can't use join method on integers. Better you check your all codes again.
Your string conversion line is under the else clause. Take it out from under the conditional, and the for loop so that it's the last thing done to encoded. As it stands, you are converting to a string halfway through your for loop:
def encode(code, msg):
'''Encrypts a message, msg, using the substitutions defined in the
dictionary, code'''
msg = list(msg)
encoded = []
for i in msg:
if i in code.keys():
i = code[i]
encoded.append(i)
else:
encoded.append(i)
# after all appends and outside for loop
encoded = ''.join(encoded)
return encoded
You are getting the error because of the second expression in you else statement.
''.join(encoded) returns a string that gets assigned to encoded
Thus encoded is now of type string.
In the second loop you have the .append(i) method in either if/else statements which can only be applied to lists and not strings.
Your .join() method should appear after the for loop right before you return it.
I apoligise if the above text does not appear right. This is my first post and I still trying to figure out how this works.

Convert Unicode data to int in python

I am getting values passed from url as :
user_data = {}
if (request.args.get('title')) :
user_data['title'] =request.args.get('title')
if(request.args.get('limit')) :
user_data['limit'] = request.args.get('limit')
Then using it as
if 'limit' in user_data :
limit = user_data['limit']
conditions['id'] = {'id':1}
int(limit)
print type(limit)
data = db.entry.find(conditions).limit(limit)
It prints : <type 'unicode'>
but i keep getting the type of limit as unicode, which raises an error from query!! I am converting unicode to int but why is it not converting??
Please help!!!
int(limit) returns the value converted into an integer, and doesn't change it in place as you call the function (which is what you are expecting it to).
Do this instead:
limit = int(limit)
Or when definiting limit:
if 'limit' in user_data :
limit = int(user_data['limit'])
In python, integers and strings are immutable and are passed by value. You cannot pass a string, or integer, to a function and expect the argument to be modified.
So to convert string limit="100" to a number, you need to do
limit = int(limit) # will return new object (integer) and assign to "limit"
If you really want to go around it, you can use a list. Lists are mutable in python; when you pass a list, you pass it's reference, not copy. So you could do:
def int_in_place(mutable):
mutable[0] = int(mutable[0])
mutable = ["1000"]
int_in_place(mutable)
# now mutable is a list with a single integer
But you should not need it really. (maybe sometimes when you work with recursions and need to pass some mutable state).

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.

Python Regular Expression TypeError

I am writing my first python program and I am running into a problem with regex. I am using regular expression to search for a specific value in a registry key.
import _winreg
import re
key = _winreg.OpenKey(_winreg.HKEY_LOCAL_MACHINE,"Software\\Microsoft\\Windows\\CurrentVersion\\Uninstall\\{26A24AE4-039D-4CA4-87B4-2F83216020FF}")
results=[]
v = re.compile(r"(?i)Java")
try:
i = 0
while 1:
name, value, type = _winreg.EnumValue(key, i)
if v.search(value):
results.append((name,value,type))
i += 1
except WindowsError:
print
for x in results:
print "%-50s%-80s%-20s" % x
I am getting the following error:
exceptions.TypeError: expected string
or buffer
I can use the "name" variable and my regex works fine. For example if I make the following changes regex doesn't complain:
v = re.compile(r"(?i)DisplayName")
if v.search(name):
Thanks for any help.
The documentation for EnumValue explains that the 3-tuple returned is a string, an object that can be any of the Value Types, then an integer. As the error explained, you must pass in a string or a buffer, so that's why v.search(value) fails.
You should be able to get away with v.search(str(value)) to convert value to a string.

Categories