1

I have this txt file:

TP 0.8329 

And i tried to extract that float after "TP" using the following code:

def definir_operacao():
    end = 0
    oper = []
    for x in range(len(lines[0])):
        if(lines[0][x] == " "):
            end += 1
        elif(end == 1):
            oper.append(int(lines[0][x]))
    str2 = ''.join(oper)
    return str2


ci = definir_operacao()
print(ci)

But i get a empty variable as response, so i guess i'm making something wrong, can anyone help me?

U13-Forward
  • 69,221
  • 14
  • 89
  • 114
  • Can you include the complete code you are working on? Including the part where you read the file. – DeusDev Jul 17 '21 at 01:52
  • if this is some kind of config file meant to be read by code, use a python file, yaml, ini, or other "code friendly" format. If it is a spreadsheet, use pandas. Reading data is a common task, so the first thing to find are the shiny tools that already exist to make your life easier – anon01 Jul 17 '21 at 01:57

2 Answers2

0

Just do this one-liner instead:

ci = float(lines[0].split()[1])

And now:

print(ci)

Would give:

0.8329
U13-Forward
  • 69,221
  • 14
  • 89
  • 114
0

You're checking that whether you get an " ", and if so you're appending the exact same " " with oper. See this segment again:

if(lines[0][x] == " "):
        end += 1
elif(end == 1):
        oper.append(int(lines[0][x]))

That is why you're getting empty as response.

just split the line on the basis of " " and take the second value from the splitting result. Don't forget to cast it to float. That will give you what you want.

res = float(lines[0].split(" ")[1])
    

You can just use split() too as @U11-Forward mentioned, because default separator is whitespace.

devReddit
  • 2,696
  • 1
  • 5
  • 20