Split an integer into digits to compute an ISBN checksum(将整数拆分为数字以计算 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 校验和的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
本文标题为:将整数拆分为数字以计算 ISBN 校验和
基础教程推荐
- kivy 应用程序中的一个简单网页作为小部件 2022-01-01
- Python 中是否有任何支持将长字符串转储为块文字或折叠块的 yaml 库? 2022-01-01
- 在 Django Admin 中使用内联 OneToOneField 2022-01-01
- 比较两个文本文件以找出差异并将它们输出到新的文本文件 2022-01-01
- 究竟什么是“容器"?在蟒蛇?(以及所有的 python 容器类型是什么?) 2022-01-01
- Kivy 使用 opencv.调整图像大小 2022-01-01
- 在 Python 中将货币解析为数字 2022-01-01
- 对多索引数据帧的列进行排序 2022-01-01
- Python,确定字符串是否应转换为 Int 或 Float 2022-01-01
- matplotlib 设置 yaxis 标签大小 2022-01-01
