Is there a simple way to replace a comma with nothing?
我正试图将字符串列表转换为浮点型,但这不能用1234.56这样的数字来实现。有没有一种方法可以使用string.replace()函数删除逗号,这样我只有1234.56?string.replace(",","")似乎不起作用。这是我当前的代码:
1 2 3 4 5 6 7 8 9 10 11 12 13 | 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) |
这是我的错误:
File"countFile.py", line 29, in main
x = float(num)
ValueError: could not convert string to float: '3,236.789'< /块引用>< /块引用>< /块引用>
在字符串上,可以替换任何字符,如
, ,如下所示:
1
2 s ="Hi, I'm a string"
s_new = s.replace(",","")此外,您对字符串所做的比较可能并不总是按照预期的方式执行。最好先转换为数值。类似:
1
2
3
4 for word in split:
n = float(word.replace(",",""))
# do comparison on n, like
# if n >= 0: ...作为提示,尝试使用
with 读取文件:
1
2
3
4
5
6
7
8 # ...
with open(fileName, 'r') as f:
for line in f:
# this will give you `line` as a string
# ending in '
' (if it there is an endline)
string_wo_commas = line.replace(",","")
# Do more stuff to the string, like cast to float and comparisons...这是一种更惯用的方法来读取文件并对每一行做一些事情。
看看这个:如果字符串中有逗号作为千位分隔符,如何使用python将其转换为数字?这个:如何使用python从字符串中删除一个字符?
另外,请注意,您的
word >=".0" 比较是string 比较,不是数值比较。他们可能不会做你认为他们会做的。例如:
1
2
3
4 >>> a = '1,250'
>>> b = '975'
>>> a > b
False