[英].strip won't remove last quotation mark in Python3 Program
编辑:更新,所以我用@Alex Thornton的建议来运行它。
这是我的输出:
'100.00"\r'
Traceback (most recent call last):
File "budget.py", line 48, in <module>
Main()
File "budget.py", line 44, in Main
budget = readBudget("budget.txt")
File "budget.py", line 21, in readBudget
p_value = float(maxamount)
ValueError: invalid literal for float(): 100.00"
但是在Windows下,我只得到数字列表,加上了引号和\\ r。
现在,我对Windows和Linux处理文本文件的方式不太了解,但这不是由于Windows和Linux处理返回/输入键的方式引起的吗?
所以我有这段代码:
def readBudget(budgetFile):
# Read the file into list lines
f = open(budgetFile)
lines = f.readlines()
f.close()
budget = []
# Parse the lines
for i in range(len(lines)):
list = lines[i].split(",")
exptype = list[0].strip('" \n')
if exptype == "Type":
continue
maxamount = list[1].strip('$" \n')
entry = {'exptype':exptype, 'maxamnt':float(maxamount)}
budget.append(entry)
#print(budget)
return budget
def printBudget(budget):
print()
print("================= BUDGET ==================")
print("Type".ljust(12), "Max Amount".ljust(12))
total = 0
for b in budget:
print(b['exptype'].ljust(12), str("$%0.2f" %b['maxamnt']).ljust(50))
total = total + b['maxamnt']
print("Total: ", "$%0.2f" % total)
def Main():
budget = readBudget("budget.txt")
printBudget(budget)
if __name__ == '__main__':
Main()
从该文件读取的内容:
"Type", "MaxAmount"
"SCHOOL","$100.00"
"UTILITIES","$200.00"
"AUTO", "$100.00"
"RENT", "$600.00"
"MEALS", "$300.00"
"RECREATION", "$100.00"
应该提取预算类型(学校,公用事业等)和最大金额。 应该将最大金额转换为浮点数。 但是,当我运行程序时,出现此错误。
Traceback (most recent call last):
File "budget.py", line 47, in <module>
Main()
File "budget.py", line 43, in Main
budget = readBudget("budget.txt")
File "budget.py", line 22, in readBudget
entry = {'exptype':exptype, 'maxamnt':float(maxamount)}
ValueError: invalid literal for float(): 100.00"
readBudget中的strip功能是否应删除最后一个引号?
当我尝试这个:
>>> attempt = '"$100.00"'
>>> new = attempt.strip('$" \n')
'100.00'
>>> float(new)
100.00
我得到的正是人们所期望的-因此这一定与我们从文件中看不到的东西有关。 从您发布的内容来看,尚不清楚您尝试传递给float()
的字符串是否存在细微的错误(因为它看起来很合理)。 尝试添加调试print
语句:
print(repr(maxamount))
p_value = float(maxamount)
然后,您可以确切确定传递给float()
。 调用repr()
可以使通常不可见的字符也可见。 将结果添加到您的问题中,我们将能够进一步发表评论。
编辑:
在这种情况下,请更换:
maxamount = list[1].strip('$" \n')
附:
maxamount = list[1].strip('$" \n\r')
那应该工作正常。
在此添加:
maxamount = list[1].strip('$" \n\r')
更具体地说,\\ r消除了错误。
您可以使用正则表达式来捕获字符串中的所有或大多数浮点信息。
考虑:
import re
valid='''\
123.45"
123.
123"
.123
123e-16
-123e16
123e45
+123.45'''
invalid='''\
12"34
12f45
e123'''
pat=r'(?:^|\s)([-+]?[0-9]*\.?[0-9]+([eE][-+]?[0-9]+)?)'
for e in [valid, invalid]:
print
for line in e.splitlines():
m=re.search(pat, line)
if m:
print '"{}" -> {} -> {}'.format(line, m.group(1), float(m.group(1)))
else:
print '"{}" not valid'.format(line)
打印:
"123.45"" -> 123.45 -> 123.45
"123." -> 123 -> 123.0
"123"" -> 123 -> 123.0
".123" -> .123 -> 0.123
"123e-16" -> 123e-16 -> 1.23e-14
"-123e16" -> -123e16 -> -1.23e+18
"123e45" -> 123e45 -> 1.23e+47
"+123.45" -> +123.45 -> 123.45
"12"34" -> 12 -> 12.0
"12f45" -> 12 -> 12.0
"e123" not valid
只需修改正则表达式即可捕获您认为有效的浮点数据点-或无效的数据点。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.