0

I am pretty sure the solution is easy but somehow the usual float doesn't work.

output = open('output.txt', 'wt')
with open('input.txt', 'r') as file:
    file = file.readlines()
    for x in range(0,len(file)):
        if file[x][0:6] == 'NUMBER':
            print(file[x][11:18]) 
            float(file[x][11:18])

print will give me '11111' , but float gives me error ValueError: could not convert string to float: What is happening here. I need it as float to do some math operation.

Update. I guess it's because i am trying to convert an empty space. The first line cause this error. float('') will give error.

NUMBER
*
NUMBER 111111111111111111111
5
  • which language is that? Please tag it Commented Mar 3, 2017 at 2:22
  • Thanks guy. Sorry my first time posting. Commented Mar 3, 2017 at 2:54
  • The error message on my Python includes the repr of the string that it couldn't convert. If that's not printing, try print(repr(file[x][11:18])) to see the repr. Might be some non-printing character (e.g. \0) embedded in the string; float ignores leading and trailing whitespace, but not arbitrary non-numeric text or embedded whitespace. Commented Mar 3, 2017 at 2:58
  • You can put a try and except condition to ignore if there is no number in the line Commented Mar 3, 2017 at 3:11
  • So what should the value be when the string is empty? Or is the line ignored? Commented Mar 3, 2017 at 3:32

1 Answer 1

2

A version of the idea that @Bijoy gave in the comments: If the problem is that the string which follows 'NUMBER' is sometimes empty and such cases should always map to the float 0.0, you can use error trapping to write a special-purpose version of float():

def getfloat(s):
    try:
        return float(s)
    except ValueError:
        return 0.0

This will work for your situation, though has the counter-intuitive behavior where e.g. getfloat("hello world") == 0.0

Sign up to request clarification or add additional context in comments.

1 Comment

Thank you. This is what I am looking for.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.