How to convert the string like '-0.88854965D+02' to float?
float('-0.88854965D+02') doesn't work:
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
ValueError: invalid literal for float(): -0.88854965D+02
The string '-0.88854965D+02' appears to be written as scientific E notation. If that is the case, then you can use the following one-liner to replace the 'D' with 'E', and then convert to a float:
n = float('-0.88854965D+02'.replace("D", "E"))
print n
-88.854965
Related
I imported a list full of floats as strings, and i tried to convert them to floats, but this error kept popping up
Traceback (most recent call last):
File "c:\Users\peter\Documents\coding\projects\LineFitting.py", line 12, in <module>
StockPriceFile = float(value.strip(''))
ValueError: could not convert string to float:
this is what i did to try and convert the list:
#1
for value in range(0, len(StockPriceFile)):
StockPriceFile[value] = float(StockPriceFile[value])
#2
for value in StockPriceFile:
value = float(value)
#3
StockPriceFile[0] = StockPriceFile[0].strip('[]')
for value in StockPriceFile:
StockPriceFile = float(value.strip(''))
(Sample Of Data)
['[36800.]', '36816.666666666664', '36816.666666666664', '36833.333333333336', '36866.666666666664']
where its being written:
Data_AvgFile.write(str(Average) + ',')
What does this mean? and how can i fix it? it works fine when i do it one by one.
(also tell me if you need more data, i dont know if this is sufficient)
for value in StockPriceFile:
stock_price = float(value.strip('[]'))
print(stock_price)
strip() will remove the [] characters around the value.
DEMO
As long you have the brackets "[ ]" in you'r string you cant convert it to a a number as that would make it invalid so do letters and most symbols the dot (.) is an exception for float.
>>> print(float('[36800.]'))
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
ValueError: could not convert string to float: '[36800.]'
>>> print(float('36800.'))
36800.0
l = ['[36800.]', '36816.666666666664', '36816.666666666664', '36833.333333333336', '36866.666666666664']
[float(f.strip('[]')) for f in l]
Output:
[36800.0,
36816.666666666664,
36816.666666666664,
36833.333333333336,
36866.666666666664]
I noticed something strange when formatting my variable into a consistent width of 11 characters:
>>> a = 1234
>>> b = None
>>> f'{a}'
'1234'
>>> f'{b}'
'None'
>>> f'{a:>11}'
' 1234'
>>> f'{b:>11}'
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
TypeError: unsupported format string passed to NoneType.__format__
You would think that using an f-string would eliminate the need for an explicit call to str, but the f-string construction gets re-routed to a call of b.__format__.
You need to ensure b is not None by calling str:
>>> f'{str(b):>11}'
' None'
I have a base64 string that I need to decode, then i convert it into a integer so I can "% 2" it. the base64 decode is easy but apparently I have some confusion on how python actually handles binary:
>>> y = 'EFbSUq0g7qvoW2ehykfSveb_pSmunxOJUEVao1RWwck'
>>> int(base64.urlsafe_b64decode('EFbSUq0g7qvoW2ehykfSveb_pSmunxOJUEVao1RWwck='), 2)
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
ValueError: invalid literal for int() with base 2: b'\x10V\xd2R\xad \xee\xab\xe8[g\xa1\xcaG\xd2\xbd\xe6\xff\xa5)\xae\x9f\x13\x89PEZ\xa3TV\xc1\xc9'
>>> int(base64.urlsafe_b64decode('EFbSUq0g7qvoW2ehykfSveb_pSmunxOJUEVao1RWwck='), 16)
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
ValueError: invalid literal for int() with base 16: b'\x10V\xd2R\xad \xee\xab\xe8[g\xa1\xcaG\xd2\xbd\xe6\xff\xa5)\xae\x9f\x13\x89PEZ\xa3TV\xc1\xc9'
>>>
Use int.from_bytes() to convert a base64 decoded string into int
int.from_bytes(
base64.urlsafe_b64decode(
'EFbSUq0g7qvoW2ehykfSveb_pSmunxOJUEVao1RWwck='
),
'big' # the endianness
)
7390406020584230016520446236832857473226268177813448430255309703833393217993
I have the Python string u'\u221220' aka "−20" with the Unicode minus sign.
When trying to convert into a float, I'm getting
>>> a = u'\u221220'
>>> float(a)
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
UnicodeEncodeError: 'decimal' codec can't encode character u'\u2212' in position 0: invalid decimal Unicode string
with Python 2 and
>>> a = u'\u221220'
>>> float(a)
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
ValueError: could not convert string to float: '−20'
with Python 3.
How can I properly convert u'\u221220' into the float -20.0 in both Python 2 and Python 3? A portable solution would be great.
From #j-f-sebastian:
a = u'\u221220'
float(a.replace(u'\N{MINUS SIGN}', '-'))
does the trick. See the related Python issue.
When I try to convert a unicode variable to float using unicodedata.numeric(variable_name), I get this error "need a single Unicode character as parameter". Does anyone know how to resolve this?
Thanks!
Here is the code snippet I'm using :
f = urllib.urlopen("http://compling.org/cgi-bin/DAL_sentence_xml.cgi?sentence=good")
s = f.read()
f.close()
doc = libxml2dom.parseString(s)
measure = doc.getElementsByTagName("measure")
valence = unicodedata.numeric(measure[0].getAttribute("valence"))
activation = unicodedata.numeric(measure[0].getAttribute("activation"))
This is the error I'm getting when I run the code above
Traceback (most recent call last):
File "sentiment.py", line 61, in <module>
valence = unicodedata.numeric(measure[0].getAttribute("valence"))
TypeError: need a single Unicode character as parameter
Summary: Use float() instead.
The numeric function takes a single character. It does not do general conversions:
>>> import unicodedata
>>> unicodedata.numeric('½')
0.5
>>> unicodedata.numeric('12')
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
TypeError: need a single Unicode character as parameter
If you want to convert a number to a float, use the float() function.
>>> float('12')
12.0
It won't do that Unicode magic, however:
>>> float('½')
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
ValueError: could not convert string to float: '½'