Is there an easy way to replace a comma with nothing?

I am trying to convert a list of strings to float, but this cannot be done with a number, e.g. 1.234.56. Is there a way to use the string.replace () function to remove a comma, so I only have 1234.56? string.replace (',', '') does not 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 get:

  
    

The file "countFile.py", line 29, in the main x = float (num) ValueError: cannot convert the string to float: '3,236.789'

    
+3
source share
2 answers

In the line, you can replace any character, for example ,, for example:

s = "Hi, I'm a string"
s_new = s.replace(",", "")

, , , , . , . - :

for word in split:
    n = float(word.replace(",", ""))
    # do comparison on n, like
    # if n >= 0: ...

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...

- .

+6

: Python , ? : python?

, word >= ".0" string , . , . :

>>> a = '1,250'
>>> b = '975'
>>> a > b
False
+2

All Articles