我正在尝试将字符串列表转换为浮点数,但这不能用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)
Run Code Online (Sandbox Code Playgroud)
这是我得到的错误:
文件"countFile.py",第29行,在main x = float(num)ValueError:无法将字符串转换为float:'3,236.789'
在字符串上,您可以替换任何字符,例如,:
s = "Hi, I'm a string"
s_new = s.replace(",", "")
Run Code Online (Sandbox Code Playgroud)
此外,您对字符串进行的比较可能并不总是按预期方式执行.最好先转换为数值.就像是:
for word in split:
n = float(word.replace(",", ""))
# do comparison on n, like
# if n >= 0: ...
Run Code Online (Sandbox Code Playgroud)
作为提示,请尝试使用以下内容读取文件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...
Run Code Online (Sandbox Code Playgroud)
这是一种更惯用的方式来读取文件并对每一行执行某些操作.
| 归档时间: |
|
| 查看次数: |
1063 次 |
| 最近记录: |