gpt4 book ai didi

python - Python 中字符串各部分的总和

转载 作者:太空宇宙 更新时间:2023-11-03 17:21:46 25 4
gpt4 key购买 nike

我正在使用 John V. Guttag 所著的《使用 Python 进行计算和编程简介》一书来学习编程。有一个练习内容如下:

'Finger exercise: Let s be a string that contains a sequence of decimal numbers separated by commas, e.g., s = '1.23,2.4,3.123'. Write a program that prints the sum of the numbers in s.'

我的尝试是:

#Finger exercise [MIT] PAGE 42     12:50 | 11.10.2015
s = ','+raw_input('Enter a string that contains a sequence of decimal numbers separated by commas, e.g. 1.23,2.4,3.123): ')+','
total = 0
for l in range(0,len(s)):
if s[l] == ',':
c = l + 1
while s[c] != ',':
c = c + 1
if s[c] == ',':
total = total + int(s[int(l),int(c)])
print total

但它一直显示此错误

TypeError: string indices must be integers, not tuple

我尝试在线寻求解决方案,但只找到了有效的解决方案,但不适用于我现在已有的内容。有什么帮助吗?

最佳答案

您在此处访问字符串项时正在创建一个元组:

s[int(l),int(c)]

逗号通常创建元组。

相反,您想在此处使用冒号来使用切片:

s[int(l):int(c)]

请注意,这两个变量都已经是整数,因此您实际上不需要转换它们:

s[l:c]

另请注意,尽管您接受 float 作为输入,但您正在对整数值求和。因此,您需要添加 float(s[l:c]),而不是添加 int(s[l:c])

关于python - Python 中字符串各部分的总和,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33067151/

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