I'm trying to convert a string list into floats but this can't be done with a number like 1,234.56. Is there a way to use the string.replace() function to remove the comma so i just have 1234.56? string.replace(',','') doesn't seem to work. This is my current code:
fileName = (input("Enter the name of a file to count: "))
print()
infile = open(fileName, "r")
line = infile.read()
split = line.split()
for word in split:
if word >= ".0":
if word <= "9":
add = (word.split())
for num in add:
x = float(num)
print(x)
This is my error I'm getting:
File "countFile.py", line 29, in main x = float(num) ValueError: could not convert string to float: '3,236.789'
On a string you can replace any character, such as ,, like so:
s = "Hi, I'm a string"
s_new = s.replace(",", "")
Also, the comparisons you are doing on the strings may not always perform the way you expect. It may be better to cast to numeric values first. Something like:
for word in split:
n = float(word.replace(",", ""))
# do comparison on n, like
# if n >= 0: ...
As a tip, try reading in your file with with:
# ...
with open(fileName, 'r') as f:
for line in f:
# this will give you `line` as a string
# ending in '\n' (if it there is an endline)
string_wo_commas = line.replace(",", "")
# Do more stuff to the string, like cast to float and comparisons...
This is a more idiomatic way to read in a file and do something to each line.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With