'int' object and 'float' object not callable error - python

I have a post request returning a list: [u'2']
I am trying to extract the number and turn it into and integer but I keep getting either 'float' object not callable or 'int' object not callable.
Here is what I have tried so far:
speed = [u'2']
strSpeed = speed[3]
intSpeed = int(strSpeed)
and
strSpeed = speed[3]
intSpeed = float(strSpeed)
and
strSpeed = speed[3]
intSpeed = int(float(strSpeed))
It seems that I can do:
print float(strSpeed)
but I can't return it.
Any ideas?

You have a list of Unicode strings:
>>> speed
[u'2']
Obtain the first item from the list, it's a Unicode string:
>>> speed[0]
u'2'
Convert this string to an integer:
>>> int(speed[0])
2
Here you are.

Your speed variable has only a single item, so you can only access index [0]
>>> int(speed[0])
2
>>> speed[0]
'2'
The u is a prefix to declare a unicode string literal. So speed is just a list with a single unicode string.

Not sure exactly what you are trying to do but if you have a list of string items and you want to extract and convert to integters or floats, you could do the following:
stringlist = ["1", "2", "3.2"]
intlistitem = int(stringlist[0])
print(intlistitem)
floatlistitem = float(stringlist[2])
print(floatlistitem)

Related

what is difference betwen string and tuple?

Can anyone explain what is difference between string and tuple
a="string"
b=("s","t","r","i","n","g")
both are immutable.
They're different types.
"str" in a # True
("s", "t", "r") in b # False
Which means they have different methods, different use cases, different meanings, different implementations, etc. etc. etc.... Consider:
datapoint_tuple = (datetime.datetime.now(), 42)
datapoint_str = ...???
Essentially the only thing they have in common is their immutability.
Strings are immutable in python which means it cannot be changed once created, if you want to update it then a new string is to be created for example.
s="Abcdef"
c=s+'112'
print s,c
you can extract value using index, find values but cannot modify it
To access substrings, use the square brackets for slicing along with the index or indices to obtain your substring
Tuple they are immutable like strings and sequence like lists.They are used to store data just like list, just like string you cannot update or edit the tuple to change it you have to create a new one just like strings.Tuples can be created using parenthesis () and data is inserted using comas.
t1=(1,2,3,'hi')
print type(t1)
print t1
A string is a sequence of unicode characters with quotation marks on either side of the sequence.
Example: mystring = "this is a string"
A tuple is an ordered sequence of objects or characters separated by commas with parentheses on either side of the sequence.
Example: mytuple = (7, "u", "p", 1, "e')
They are, however, similar in the fact that they are both immutable
t1 = (1,2,3,4)
t2 =(1,2,3,4)
print( t1 is t2)
Output: True
This means they refer to the same object and string does the same thing. But tuples comes into play when few data need to stay together. For example: file name, it's size and type. Even when you return multiple values they are returned as a tuple.
def convert_seconds(seconds):
hours = seconds//3600
minutes = (seconds - hours*3600)//60
remaining_seconds = seconds- hours*3600 - minutes*60
return hours,minutes,remaining_seconds
result = convert_seconds(5000)
print(type(result))
output: <class 'tuple'>
Once you know why using it, it will clear your confusion.
tuple use a trailing comma:
tuple_a = 'a',
print(type(tuple_a)) # <class 'tuple'>
string don't use:
string_a = 'a'
print(type(string_a)) # <class 'str'>
but string and tuple has some same characteristics。
eg:
1、indexing and slicing
string_same = 'string'
tuple_same = ('s', 't', 'r', 'i', 'n', 'g')
print(string_same[0], tuple_same[0]) # s s
print(string_same[:-1], tuple_same[:-1]) # strin ('s', 't', 'r', 'i', 'n')
2、Immutability
means string and tuple not suport item assigment
string_same[0] = 'python_'
tuple_same[0] = 'python_'
TypeError: 'str' object does not support item assignment
TypeError: 'tuple' object does not support item assignment
you could find all of the diffrent from the Doc.
including other tyeps build-in types.
https://docs.python.org/3/library/stdtypes.html?highlight=tuple#tuple

remove spaces from csv field but ignoring datetime objec

i have a csv that is a result of a DB2 query.
For some reason the csv is created like this
"filed1 ", "field2, ","2017-11-24"
i'm able to remove the white spaces inside field with this:
for result in results:
result = [x.strip(' ') for x in result]
csvwriter.writerow(result)
but the date field is <type 'datetime.date'> so i get the error
AttributeError: 'datetime.date' object has no attribute 'strip'
How can i apply the strip function only to string object? Or can i transform the datetime.date object in str object?
Thanks very much
You could change your list comprehension as follows:
result = [str(x).strip() for x in result]
This will first convert all the cells to a string and then apply the strip() on that. Or more directly as follows:
csvwriter.writerow([str(x).strip() for x in result])
Just check the type before:
if isinstance(x,str):
...

Python: Concatenate url with a integer

I'm new in python and I'm trying to concatenate an url with an integer but i get this error:
TypeError: cannot concatenate 'str' and 'int' objects*
My code looks like this:
for x in range(0,10):
url = "http:www.eluniversal.com.mx/minuto-x-minuto?seccion=All&page="+(x)
x +=1
Can someone help me?
Python is a dynamically strongly typed langauge. So it won't convert an integer to string when you try to concatenate them.
You have to either use string interpolation or explicitly convert it to an string.
url = "http:www.eluniversal.com.mx/minuto-x-minuto?seccion=All&page=%s" % x
url = "http:www.eluniversal.com.mx/minuto-x-minuto?seccion=All&page=" + str(x)
url = "http:www.eluniversal.com.mx/minuto-x-minuto?seccion=All&page="+str(x)
Add a "str" in front of your brackets and it will work. By doing this you can convert the int into a string.
url += str(x)
x+=1 has no effect.

Converting a list to string in python 2.7

I have a list xline. It is initialized and then appended. But I am getting an error when I run?
xline = []
---#append
----
print (''.join(xline)) # Convert list into string
Run time error
print (''.join(xline)) # Convert list into string
TypeError: sequence item 0: expected string, int found
What is wrong?
You can use str() to transform each element:
print ''.join([str(x) for x in xline])

Python: 'int' object is not subscriptable

I am getting an error here and I am wondering if any of you can see where I went wrong. I am pretty much a beginner in python and can not see where I went wrong.
temp = int(temp)^2/key
for i in range(0, len(str(temp))):
final = final + chr(int(temp[i]))
"temp" is made up of numbers. "key" is also made of numbers. Any help here?
First, you defined temp as an integer (also, in Python, ^ isn't the "power" symbol. You're probably looking for **):
temp = int(temp)^2/key
But then you treated it as a string:
chr(int(temp[i]))
^^^^^^^
Was there another string named temp? Or are you looking to extract the ith digit, which can be done like so:
str(temp)[i]
final = final + chr(int(temp[i]))
On that line temp is still a number, so use str(temp)[i]
EDIT
>>> temp = 100 #number
>>> str(temp)[0] #convert temp to string and access i-th element
'1'
>>> int(str(temp)[0]) #convert character to int
1
>>> chr(int(str(temp)[0]))
'\x01'
>>>

Categories