I have a large file with numbers in the form of 6,52353753563E-7. So there's an exponent in that string. float() dies on this.
While I could write custom code to pre-process the string into something float() can eat, I'm looking for the pythonic way of converting these into a float (something like a format string passed somewhere). I must say I'm surprised float() can't handle strings with such an exponent, this is pretty common stuff.
I'm using python 2.6, but 3.1 is an option if need be.
Nothing to do with exponent. Problem is comma instead of decimal point.
>>> float("6,52353753563E-7")
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
ValueError: invalid literal for float(): 6,52353753563E-7
>>> float("6.52353753563E-7")
6.5235375356299998e-07
For a general approach, see locale.atof()
Your problem is not in the exponent but in the comma.
with python 3.1:
>>> a = "6.52353753563E-7"
>>> float(a)
6.52353753563e-07
Related
Shouldn't both these commands do the same thing?
>>> "{0[0:5]}".format("lorem ipsum")
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
TypeError: string indices must be integers
>>> "{0}".format("lorem ipsum"[0:5])
'lorem'
The commands
>>> "{0[0]}".format("lorem ipsum")
'l'
and
>>> "{0}".format("lorem ipsum"[0])
'l'
evaluate the same. (I know that I can use other methods to do this, I am mainly just curious as to why it dosen't work)
The str.format syntax is handled by the library and supports only a few “expression” syntaxes that are not the same as regular Python syntax. For example,
"{0[foo]}".format(dict(foo=2)) # "2"
works without quotes around the dictionary key. Of course, there are limitations from this simplicity, like not being able to refer to a key with a ] in it, or interpreting a slice, as in your example.
Note that the f-strings mentioned by kendall are handled by the compiler and (fittingly) use (almost) unrestricted expression syntax. They need that power since they lack the obvious alternative of placing those expressions in the argument list to format.
I have some fairly hairy unicode strings with numbers in them that I'd like to test the value of. Normally, I'd just use str.isnumeric to test for whether it could be converted via int() but I'm encountering cases where isnumeric returns True but int() raises an exception.
Here's an example program:
>>> s = '⒍'
>>> s.isnumeric()
True
>>> int(s)
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
ValueError: invalid literal for int() with base 10: '⒍'
Unicode is always full of surprises, so I'm happy to just be robust to this case and use a try/except block to catch unusual numbers. However, I'd be happier if I could still convert them to integers. Is there a consistent way to do this?
If you want to test if a string can be passed to int, use str.isdecimal. Both str.isnumeric and str.isdigit include decimal-like characters that aren't compatible with int.
And as #abarnert has mentioned in the comments, the most guaranteed way to test if a string can be passed to int is to simply do it in a try block.
On the other hand, '⒍' can be converted to an actual digit with the help of the unicodedata module, e.g.
print(unicodedata.digit('⒍'))
would output 6.
I don't know how much luck you'll have, but unicodedata may handle some cases (python 3 code):
>>> import unicodedata
>>> unicodedata.normalize('NFKC', '⒍')
'6.'
Slightly better. As to testing, if you want an int you could just int() it and catch the exception.
The best way to find out if a string can be converted to int is to just try it:
s = '⒍'
try:
num = int(s)
except ValueError:
# handle it
Sure, you can try to figure out the right way to test the string in advance, but why? If the rule you want is "whatever int accepts", just use int.
If you want to convert something that is a digit, but isn't a decimal, use the unicodedata module:
s = '⒍'
num = unicodedata.digit(s) # 6
num = unicodedata.numeric(s) # 6.0
num = unicodedata.decimal(s) # ValueError: not a decimal
The DIGIT SIX FULL STOP character's entry in the database has Digit and Numeric values, despite being a Number, Other rather than a Number, Decimal Digit (and therefore not being compatible with int).
Hi I'm getting TypeError and i just don't know why...
x=float(40)
base=float(10)
math.log(x, [base])
Traceback (most recent call last):
File "<string>", line 1, in <fragment>
TypeError: a float is required
math.log(x, [base]) doesn't literally mean "put base in brackets". This is what the documentation uses to denote an optional argument.
Remove them and it'll work
math.log(x, base)
Also, you don't need to use the float builtin to declare floats. Just add on a decimal component to your number and it will become a float:
x = 40.0
math.log(x, 10)
i am new in python, i just try to play a video in avg player through python. All the videos are played successfully, but one video has through this value error. i am not sure why this error was happened . if you know describe me.
The specific problem arises because the software tries to interpret 107.24 as an integer number, which it is not.
Why it does this, or where this number is coming from, is really hard to tell from the little information given in your question.
'107.24' is a float string and int() can't convert a float string, use float().
>>> a='107.24'
>>> int(a)
Traceback (most recent call last):
File "<pyshell#1>", line 1, in <module>
int(a)
ValueError: invalid literal for int() with base 10: '107.24'
>>> float(a)
107.24
I am running a code to select chunks from a big file. I am getting some strange error that is
"Invalid literal for float(): E-135"
Does anybody know how to fix this? Thanks in advance.
Actually this is the statement that is giving me error
float (line_temp[line(line_temp)-1])
This statement produces error
line_temp is a string
'line' is any line in an open and file also a string.
You need a number in front of the E to make it a valid string representation of a float number
>>> float('1E-135')
1e-135
>>> float('E-135')
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
ValueError: invalid literal for float(): E-135
In fact, which number is E-135 supposed to represent? 1x10^-135?
Valid literal forms for floats are here.
Looks like you are trying to convert a string to a float. If the string is E-135, then it is indeed an invalid value to be converted to a float. Perhaps you are chopping off a digit in the beginning of the string and it really ought to be something like 1E-135? That would be a valid float.
May I suggest you replace
float(x-y)
with
float(x) - float(y)
Ronald, kindly check the answers again. They are right.
What you are doing is: float(EXPRESSION), where the result of EXPRESSION is E-135. E-135 is not valid input into the float() function. I have no idea what the "line_temp[line(line_temp)-1]" does, but it returns incorrect data for the float() function.