gpt4 book ai didi

python - 有什么简单的方法可以用什么替换逗号吗?

转载 作者:太空宇宙 更新时间:2023-11-03 13:00:54 26 4
gpt4 key购买 nike

我正在尝试将字符串列表转换为 float ,但这不能用像 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)

这是我得到的错误:

File "countFile.py", line 29, in main x = float(num) ValueError: could not convert string to float: '3,236.789'

最佳答案

在一个字符串上你可以替换任何字符,比如,,像这样:

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

这是一种更惯用的方式来读取文件并对每一行做一些事情。

关于python - 有什么简单的方法可以用什么替换逗号吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21897233/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com