将整数拆分为数字以计算 ISBN 校验和
问题描述
我正在编写一个计算 ISBN 号校验位的程序.我必须将用户的输入(ISBN 的九位数字)读入一个整数变量,然后将最后一位数字乘以 2,倒数第二位乘以 3,依此类推.我怎样才能将整数拆分"成它的组成数字来做到这一点?由于这是一项基本的家庭作业,我不应该使用列表.
I'm writing a program which calculates the check digit of an ISBN number. I have to read the user's input (nine digits of an ISBN) into an integer variable, and then multiply the last digit by 2, the second last digit by 3 and so on. How can I "split" the integer into its constituent digits to do this? As this is a basic homework exercise I am not supposed to use a list.
解决方案
只需创建一个字符串.
myinteger = 212345
number_string = str(myinteger)
够了.现在您可以对其进行迭代:
That's enough. Now you can iterate over it:
for ch in number_string:
print ch # will print each digit in order
或者你可以切片:
print number_string[:2] # first two digits
print number_string[-3:] # last three digits
print number_string[3] # forth digit
<小时>
或者更好的是,不要将用户的输入转换为整数(用户键入字符串)
Or better, don't convert the user's input to an integer (the user types a string)
isbn = raw_input()
for pos, ch in enumerate(reversed(isbn)):
print "%d * %d is %d" % pos + 2, int(ch), int(ch) * (pos + 2)
有关更多信息,请阅读教程.
For more information read a tutorial.
相关文章