-1

I am trying to understand this error message (Python 2.7). I see there are others who have asked this question previously, but I do not understand the explanations given there so I am asking again.

Here is my code:

import re
name = raw_input("Enter file:")
if len(name) < 1 : name = "file.txt"
handle = open(name)
y = list()
for line in handle:
    line = line.rstrip()
    if re.findall('[0-9]+', line) != [] :        
        y.append(re.findall('[0-9]+', line))
a = [map(int, b) for b in y]
for x in range(len(a)):
    if len(a[x]) == 1:
        b=str(a[x])
        c=float(b)
halfer
  • 19,824
  • 17
  • 99
  • 186
  • Can you provide some links to the previous posts? – Tankobot Mar 19 '17 at 02:37
  • please go through hope you can find your answers: http://stackoverflow.com/questions/8420143/valueerror-could-not-convert-string-to-float-id – manoj Mar 19 '17 at 02:54
  • It looks like your attempting to convert the string '[9000]' into a float, which won't work because it has those extra brackets. You can either fix this in your file that you are reading, or you can remove the brackets by splicing it out: ``"[9000]"[1:-1] == "9000"``. – Tankobot Mar 19 '17 at 03:04

1 Answers1

1

you will see what is happening if you print more often

you have created a list of lists

so a[x] is itself a list

when you stringify the list its '[9000]'

so you can't make a float out of that because its not a number

you would have to strip the brackets; or not create a list of lists to begin with

using your post as input:

import re
handle = '''
Python - ValueError: could not convert string to float: [9000]
Ask Question
up vote
0
down vote
favorite


I am trying to understand this error message (Python 2.7). I see there are 
others who have asked this question previously, but I do not understand the 
explanations given there so I am asking again. Here is my code. Yes, I am a 
newbie trying to learn the basics so please keep that in mind when you answer.
There's a reason I haven't been able to understand previous posts.
'''
y = list()
print y
for line in handle:
    line = line.rstrip()
    if re.findall('[0-9]+', line) != [] :        
        y.append(re.findall('[0-9]+', line))

print y
a = [map(int, b) for b in y]
print a
for x in range(len(a)):
    if len(a[x]) == 1:
        b=str(a[x])
        print b
        c=float(b)

returns:

[]
[['9'], ['0'], ['0'], ['0'], ['0'], ['2'], ['7']]
[[9], [0], [0], [0], [0], [2], [7]]
[9]
Traceback (most recent call last):
  File "test4.py", line 31, in <module>
    c=float(b)
ValueError: could not convert string to float: [9]

I'm not sure what your end goal is, but if you did this:

b=str(a[x][0])
print b
c=float(b)

it would work and return

9
0
0
0
0
2
7
litepresence
  • 3,109
  • 1
  • 27
  • 35