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.
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.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With