是否有一种简单的方法来替换没有任何内容的逗号?

时间:2014-02-20 03:01:38

标签: python

我正在尝试将字符串列表转换为浮点数,但这不能用1,234.56这样的数字来完成。 有没有办法使用string.replace()函数删除逗号所以我只有1234.56? string.replace(',','')似乎不起作用。这是我目前的代码:

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)

这是我的错误:

  
    
      
        

文件“countFile.py”,第29行,在main中             x = float(num)         ValueError:无法将字符串转换为float:'3,236.789'

      
    
  

2 个答案:

答案 0 :(得分:6)

在字符串上,您可以替换任何字符,例如,,如下所示:

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

这是一种更习惯的方式来读取文件并对每一行执行某些操作。

答案 1 :(得分:2)

请查看以下内容:How do I use Python to convert a string to a number if it has commas in it as thousands separators?和此:How to delete a character from a string using python?

另请注意,您的word >= ".0"比较是string比较,而不是数字。他们可能不会按照你的想法去做。例如:

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