当字符串上的最后一个索引有“x”或“X”(它表示为 10)时,如果我有类似“1x”的东西,这意味着 11 (1 + 10)
def main():
s1 = "013162959x"
partial_sums(s1)
def partial_sums(s1):
lst =[]
sum = 0
for i in range(len(s1)):
if (i == len(s1) -1) and (s1[i] == "x" or "X"):
sum = sum + int(s1[i]) + 10
else:
sum = sum + int(s1[i])
lst.append(sum)
print(lst)
main()
我得到一个 ValueError: invalid literal for int() with base 10: 'x'
输出应该是 [0, 1, 4, 5, 11, 13, 22, 27, 36, 46]
当字符串不包含“X”值时,它可以正常工作。
def main():
s1 = "0131629592"
partial_sums(s1)
def partial_sums(s1):
lst1 =[]
sum = 0
for i in range(len(s1)):
sum = sum + int(s1[i])
lst1.append(sum)
print(lst1)
main()
我该如何解决?