Python 有没有一种简单的方法可以将逗号替换为空?

Python 有没有一种简单的方法可以将逗号替换为空?,python,Python,我正在尝试将字符串列表转换为浮点数,但无法使用像1234.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

我正在尝试将字符串列表转换为浮点数,但无法使用像1234.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)
fileName=(输入(“输入要计数的文件名:”)
打印()
infle=open(文件名为“r”)
line=infle.read()
split=line.split()
对于拆分中的单词:
如果单词>=“.0”:

如果字符串上有单词,则可以替换任何字符,如
,如下所示:

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 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...
这是一种更为惯用的方式来读取文件并对每一行执行操作。

查看以下内容:以及以下内容:

另外,请注意,您的
word>=“.0”
比较是
string
比较,而不是数字比较。他们可能不会做你认为他们会做的事。例如:

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

如果有关系,我想打印最后一步的浮点总数。只需使用str.replace()函数我尝试在代码的各个部分添加此函数,但出现了以下错误:AttributeError:“list”对象没有属性“replace”
replace
是一个字符串方法。它只能用于字符串,而不能用于字符串列表(或任何其他相关内容的列表)。我已经用一个例子更新了我的答案,说明了如何将文件中的每一行作为字符串读取,并更轻松地对其执行一些操作。希望能有帮助。我正在从文本文件中提取数字。有没有更好的方法只提取数字而不获取它们之间的单词?如果不知道文件中文本和数字的格式,很难回答这个问题,但是可以使用正则表达式。例如,您可以标记文本,然后选择处理与正则表达式
[0-9]+、?[0-9]+\[0-9]+
或其他内容匹配的任何内容。您可以简化它并处理任何以
[0-9]
开头的令牌(在Python
re
模块中查找
search()
match()