I have a file, variables.txt, when I input a float, say 7.75, it inputs it into the file as 7.75. When I get the information back from the file, I get ['7.75']. I'm assuming this is a list. How would I be able to change ['7.75'] back to a float, 7.75, so that it can be multiplied, divided, etc.
3 Answers
Cast the first entry in the list to a float() value:
value = float(somelist[0])
5 Comments
micma
what does somelist stand for? If you open up the file, all you see is 7.75. There isnt anything else there like variable = 7.75
Martijn Pieters
@user3133761: The original variable you printed, with the list. You did not include any actual code, so I had to guess at your variable names.
abarnert
@user3133761: According to your question, you have a value
['7.75'] appearing somewhere in your code. Since you didn't tell us where that value appears, Martijn had to invent a name for a variable to hold that value, and somelist is a perfectly reasonable name for a variable holding a list of strings.micma
sorry for the confusion.
Martijn Pieters
@user3133761: Not a problem. I'd love to help you in more detail, but you haven't given us any code to work with. If this answer helped you, then that's fine too, don't forget to mark it as such. :-)
This code will open a text file with a float on each line and give you a list of floats
with open('floats.txt', 'r') as f:
floats = []
for each in f:
floats.append(float(each.strip()))
print(floats)
you can then access each float in the list by it's index:
float[0] #this will give you the first entry in the list
File:
7.75
1.23
4.56
Output:
[7.75, 1.23, 4.56]
Comments
In Python, how do I convert all of the items in a list to floats?
To reiterate, you want to loop through the list and convert all element to float values using the "float" function.
['7.75']and would like to have7.75. See SSCCE for guidance.['7.75'], and the answers are about trying to convert to float-or-int-as-appropriate rather than just to float.open('foo.txt').readlines().