[英]How to append a check digit to a number
好的,我想做的是在用户输入的数字的末尾附加一个校验位。这是代码。 我会在后面解释。
isbn_list = ["0", "1", "2", "3", "4", "5", "6", "7", "8", "9"]
isbn = [0,1,2,3,4,5,6,7,8,9]
isbnMult = [11,10,9,8,7,6,5,4,3,2,1]
number = input("Input ISBN number: ")
isbnnumber= 0
for i in range(len(number)):
found= False
count= 0
while not found:
if number[i] == isbn_list[count]:
found= True
isbnnumber= isbnnumber + isbn[count] * isbnMult[i]
else:
count += 1
total=isbnnumber%11
checkdigit=11-total
check_digit=str(checkdigit) #I know I have to append a number to a string
number.append(checkdigit) #so i thought that I would make the number into a
print(number) #string and then use the '.append' function to add
#it to the end of the 10 digit number that the user enters
但这不起作用
它给了我这个错误:
number1.append(checkdigit)
AttributeError: 'str' object has no attribute 'append'
根据我的经验,我只能猜测那意味着我不能追加字符串? 关于如何将校验位追加到用户输入的号码末尾的任何想法或建议?
您无法在Python中修改字符串。 因此,没有添加方法。 但是,您可以创建一个新字符串并将其分配给变量:
>>> s = "asds"
>>> s+="34"; s
'asds34'
append
用于数组。 如果要连接字符串,请尝试仅使用+
。
>>> '1234' + '4'
'12344'
Python中有两种类型的对象:可变对象和不可变对象。 可变对象是可以就地修改的对象,顾名思义,不可变对象不能就地更改,但是对于每次更新,都需要创建一个新字符串。
因此,字符串对象没有append方法,这意味着需要就地修改字符串。
所以你需要换线
number1.append(checkdigit)
至
number1 += checkdigit
注意
尽管后面的语法看起来像是就地附加,但是在这种情况下,它替换为number1 = number1 + checkdigit
,最终创建了一个新的不可变字符串。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.