将整数拆分为数字以计算ISBN校验和 [英] Split an integer into digits to compute an ISBN checksum

查看:212
本文介绍了将整数拆分为数字以计算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.

这篇关于将整数拆分为数字以计算ISBN校验和的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆