Python
Programming Exercises, Gently Explained
96
result in a variable named onesPlaceDigit.
Then we add the string equivalent of onesPlaceDigit to stringNum with a series of if-
elif
statements such as the following:
if onesPlaceDigit == 0:
stringNum = '0' + stringNum
elif onesPlaceDigit == 1:
stringNum = '1' + stringNum
elif onesPlaceDigit == 2:
stringNum = '2' + stringNum
elif onesPlaceDigit == 3:
stringNum = '3' + stringNum
elif onesPlaceDigit == 4:
stringNum = '4' + stringNum
elif onesPlaceDigit == 5:
stringNum = '5' + stringNum
elif onesPlaceDigit == 6:
stringNum = '6' + stringNum
elif onesPlaceDigit == 7:
stringNum = '7' + stringNum
elif onesPlaceDigit == 8:
stringNum = '8' + stringNum
elif onesPlaceDigit == 9:
stringNum = '9' + stringNum
However, this code is pretty long and tedious. A more concise and common approach is to create
a dictionary that maps individual integer digits to their string
equivalents, and then look up the value
for the onesPlaceDigit key:
DIGITS_INT_TO_STR = {0: '0', 1: '1', 2: '2', 3: '3', 4: '4', 5: '5', 6: '6', 7: '7',
8: '8', 9: '9'}
stringNum = DIGITS_INT_TO_STR[onesPlaceDigit] + stringNum
After this, we can integer divide it by 10 to ―remove‖ the digit in the one’s place of
integerNum
. For example, 41096 // 10 evaluates to 4109, effectively removing the 6 from the
number and making the 9 the new digit in the one’s place to convert. Our loop can continue looping
and converting digits until integerNum is 0. For example, doing this to the integer 41096 would
carry out the following operations:
41096 // 10 = 4109
4109 // 10 = 410
410 // 10 = 41
41 // 10 = 4
4 // 10 = 0
At this point the algorithm is finished and stringNum contains the string form.
Dostları ilə paylaş: