Converting a string into a float that includes the negative

Pete Dowdell contact at stridebird.com
Sat Nov 7 21:39:00 EST 2015


On 08/11/15 09:11, phamtony33 at gmail.com wrote:
> I am having issue with converting the string into a float because there is a negative, so only end up with "ValueError: invalid literal for float(): 81.4]"81.4]

The error is right there in the exception: you are trying to cast 
'81.4]' - that's a square bracket in the string.
You are also  removing the negative sign from your number before casting 
with your slice

this will fix it - change line:
long1 = long[1:]
to:
long1 = long[:-1]

test:
 >>> TXT="[41.3, -81.4]\t6\t2011-08-28 19:02:28\tyay. little league 
world series!"
 >>> float( TXT.split('\t')[0].split(', ')[1][:-1] )
-81.4

pd



More information about the Python-list mailing list