ValueError: could not convert string to float on heroku [closed] - python

Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed last year.
Improve this question
I am a beginner and need help with converting str to float on python.
the code seems to work fine locally, but when I deploy on heroku I get
"ValueError: could not convert string to float".
Is anybody else experiencing this? It would be great if you could help me.
2022-01-26T14:40:03.536858+00:00 app[web.1]:
tx_count = float(raw_data["result"].replace("0x", ""))
2022-01-26T14:40:03.536858+00:00 app[web.1]:
#ValueError: could not convert string to float: 'Invalid API Key'
my code:
my_address = request.form["public_key"]
response = requests.get(f"https://api.etherscan.io/api?module=proxy&action=eth_getTransactionCount&address={my_address}&tag=latest&apikey={API_KEY}")
raw_data = response.json()
raw_data:
raw_data = {
'jsonrpc': '2.0',
'id': 1,
'result': '0x3'
}
I want raw_data["result"] to be a number because I want to use the number to calculate.
I created a repository on github
https://github.com/yataishiba/co2-calc-eth
UPDATE
I tried this but it is still not working...
Convert hex string to int in Python

You can't throw hex directly at float() because the string can contain non-numerical strings; i.e. A-F.
Instead you should use float.fromhex(). This will also let you not use .replace(). For example:
tx_count = float.fromhex(raw_data["result"])

Related

ValueError: '=' alignment not allowed in string format specifier. Sometimes not working [closed]

Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 1 year ago.
Improve this question
Error message:
alarm = f"{alarm_hour}:{alarm_minute:02}:{alarm_am_pm}"
ValueError: '=' alignment not allowed in string format specifier
I don't know why this code is giving the error as I have used the same before in the 's program and it's working fine. Here's the code.
TIME = f"{current_hour}:{current_minute:02}:{current_second} {am_pm}"
But whenever I remove :02 from alarm_minute it works as I wanted to show number in 2 digits. I'm confused what's wrong with the code. Both are almost identical but one is giving error other's don't.
Assuming you want to have the number formated as a two digit with leading 0 when its a single digit you can pass this with the letter d to let the fstring know you want to format as 2 digits leaded by 0. you can do similar with floats to print to x many decimal places.
num = 3
price = 4.9
print(f"{num:02d}, {price:.2f}")
OUTPUT
03, 4.90

why I got an error ''float' object is not iterable' while using apply lambda [closed]

Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 2 years ago.
Improve this question
I try to convert a list of Chinese province into pinyin use pinyin package, code like below:
df['province'] = df['comb_province'].apply(lambda x: pinyin.get(x, format="strip", delimiter=''))
but I got an error says: 'float' object is not iterable. Why this happens? How can I fix it?
Thank you!
You may have been encountered numpy.nan or None values in the df["comb_province"] column. So, you could try to remove those rows with numpy.nan by using the following code:
df = df[~df["comb_province"].isnull()]
or if you wish to keep the rows with numpy.nan or None, then using the following:
df["comb_province"] = df["comb_province"].astype(str)
Your original code may be of strip or split, something related to string operations, which will throw an error when encountering either numpy.nan or None.

Converting from list to string to int in Python- int() function not working [closed]

Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 3 years ago.
Improve this question
I have looked and can't find anything to answer my question.
I am using sample() function for random numbers, but it returns a list.
I have found an easy way to convert it into a string, but the int() function IS NOT working to turn it into an integer. How can I fix this? Is there a way I can skip out converting to a string?
Below is the code I am using:
from random import sample
def ver1():
qval = sample(range(1, 6),1)
#This converts qval from a list to a string:
qval_str = ''.join(map(str, qval))
#This converts qval from a string to an integer
int(qval_str)
print(qval_str)
ver1()
Thanks in advance,
hxhu
You are not saving the result of int() anywhere:
from random import sample
def ver1():
qval = sample(range(1, 6),1)
# This converts qval from a list to a string:
qval_str = ''.join(map(str, qval))
# this creates an integer from qval
ival=int(qval_str)
print(qval_str)
print(ival)
ver1()
int() returns the parsed integer as its return value - you need to save it in a variable to use it in the future
If you want a single value (as in your example usage of random.sample()), just use random.choice() instead.

extract json by Python [closed]

Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 6 years ago.
Improve this question
I have this JSON
myJson = [{"linkId":"changeDriveLink","url":"/drive/rayon.header.changedrivelink?t:ac=3686962/3696434","zoneId":"forceAjax"},
{"linkId":"affichePopinProduit","url":"/drive/rayon.header.promosmenu.thumbnailproduct.affichepopinproduit/804106/Paysan$0020Breton$0020beurre$0020moul$00e9$0020demi-sel$0020250g/$N?t:ac=3686962/3696434","zoneId":"forceAjax"},
{"linkId":"addProductToShoppingList2","url":"/drive/rayon.header.promosmenu.thumbnailproduct.addproducttoshoppinglist2/804106/Paysan$0020Breton$0020beurre$0020moul$00e9$0020demi-sel$0020250g?t:ac=3686962/3696434","zoneId":"forceAjax"}]
i want to have the URLS, i tried :
decoded = json.loads(myJson.read())
and
decoded = json.load(myJson.read())
and
decoded = json.load(myJson)
but I always have this error:
AttributeError: 'str' object has no attribute 'read'
How about:
decoded = json.loads(myJson)
which doesn't give any errors when I run it.
You don't need read(), just dump it (if you don't have it in string representation) and then load it.
import json
myJson = [{"linkId":"changeDriveLink","url":"/drive/rayon.header.changedrivelink?t:ac=3686962/3696434","zoneId":"forceAjax"},{"linkId":"affichePopinProduit","url":"/drive/rayon.header.promosmenu.thumbnailproduct.affichepopinproduit/804106/Paysan$0020Breton$0020beurre$0020moul$00e9$0020demi-sel$0020250g/$N?t:ac=3686962/3696434","zoneId":"forceAjax"},{"linkId":"addProductToShoppingList2","url":"/drive/rayon.header.promosmenu.thumbnailproduct.addproducttoshoppinglist2/804106/Paysan$0020Breton$0020beurre$0020moul$00e9$0020demi-sel$0020250g?t:ac=3686962/3696434","zoneId":"forceAjax"}]
myJson = json.dumps(myJson)
json.loads(myJson)
The result is a list of dicts:
[{'linkId': 'changeDriveLink',
'url': '/drive/rayon.header.changedrivelink?t:ac=3686962/3696434',
'zoneId': 'forceAjax'},
{'linkId': 'affichePopinProduit',
'url': '/drive/rayon.header.promosmenu.thumbnailproduct.affichepopinproduit/804106/Paysan$0020Breton$0020beurre$0020moul$00e9$0020demi-sel$0020250g/$N?t:ac=3686962/3696434',
'zoneId': 'forceAjax'},
{'linkId': 'addProductToShoppingList2',
'url': '/drive/rayon.header.promosmenu.thumbnailproduct.addproducttoshoppinglist2/804106/Paysan$0020Breton$0020beurre$0020moul$00e9$0020demi-sel$0020250g?t:ac=3686962/3696434',
'zoneId': 'forceAjax'}]
here is no need to 'loads' or 'dumps'. you are have already proper list-dict data.
for 'url's just use
[i['url'] for i in myJson]

Getting rid of square brackets on either side of a string [closed]

Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 7 years ago.
Improve this question
I am importing currency exchange rates from a website. All is well, except python prints the required data as follows:
['12.3098']
which means I can't use the data that I scraped in any calculations in my program. How do I get rid of the square brackets so that I can convert the string inside the square brackets to a float?
you have a list which is not a string... so if you want to get that value out select it like so
float(result[0])
replace 'result' with whatever your object is, aka what you printed ['12.3098']
try printing the type of your object type(result) and if its a list then this will fix your problem
if the type is a string you can do a literal evaluation of it like this
import ast
result = ast.literal_eval(result)
print result[0]

Categories

Resources