Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Split an integer into digits to compute an ISBN checksum

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.

like image 215
zequzd Avatar asked Jun 10 '09 11:06

zequzd


People also ask

Does split function work on integer?

split() functions to split an integer into digits in Python. Here, we used the str. split() method to split the given number in string format into a list of strings containing every number. Then the map() function is used, which is utilized to generate a map object which converts each string into an integer.


1 Answers

Just create a string out of it.

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 

Or you can slice it:

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.

like image 152
nosklo Avatar answered Sep 17 '22 17:09

nosklo