P ython p rogramming e xercises


Exercise #32: Convert Strings to Integers



Yüklə 1,51 Mb.
Pdf görüntüsü
səhifə120/124
tarix14.05.2023
ölçüsü1,51 Mb.
#113537
1   ...   116   117   118   119   120   121   122   123   124
PythonProgrammingExercisesGentlyExplained

Exercise #32: Convert Strings to Integers 
def convertStrToInt(stringNum): 
# This dictionary maps string digits to single integer digits: 
DIGITS_STR_TO_INT = {'0': 0, '1': 1, '2': 2, '3': 3, '4': 4, 
'5': 5, '6': 6, '7': 7, '8': 8, '9': 9} 
# Make a note whether the number is negative or not, and make 
# integerNum positive for the rest of the function's code: 
if stringNum[0] == '-': 
isNegative = True 
stringNum = stringNum[1:] 
else: 
isNegative = False 
# integerNum holds the converted integer, and starts off at 0:
integerNum = 0 
# Loop over the digits in the string from left to right: 
for i in range(len(stringNum)): 
# Get the integer digit from the string digit: 
digit = DIGITS_STR_TO_INT[stringNum[i]] 
# Add this to the integer number: 
integerNum = (integerNum * 10) + digit 
# If the number was originally negative, make the integer 


Python Programming Exercises, Gently Explained 
147 
# negative before returning it: 
if isNegative: 
return -integerNum 
else: 
return integerNum 
Exercise #33: Comma-Formatted Numbers 
def commaFormat(number): 
# Convert the number to a string: 
number = str(number) 
# Remember the fractional part and remove it from the number, if any: 
if '.' in number: 
fractionalPart = number[number.index('.'):] 
number = number[:number.index('.')] 
else: 
fractionalPart = '' 
# Create a variable to hold triplets of digits and the 
# comma-formatted string as it is built: 
triplet = '' 
commaNumber = '' 
# Loop over the digits starting on the right side and going left: 
for i in range(len(number) - 1, -1, -1): 
# Add the digits to the triplet variable: 
triplet = number[i] + triplet 
# When the triplet variable has three digits, add it with a 
# comma to the comma-formatted string: 
if len(triplet) == 3: 
commaNumber = triplet + ',' + commaNumber 
# Reset the triplet variable back to a blank string: 
triplet = '' 
# If the triplet has any digits left over, add it with a comma 
# to the comma-formatted string: 
if triplet != '': 
commaNumber = triplet + ',' + commaNumber 
# Return the comma-formatted string: 
return commaNumber[:-1] + fractionalPart 

Yüklə 1,51 Mb.

Dostları ilə paylaş:
1   ...   116   117   118   119   120   121   122   123   124




Verilənlər bazası müəlliflik hüququ ilə müdafiə olunur ©azkurs.org 2025
rəhbərliyinə müraciət

gir | qeydiyyatdan keç
    Ana səhifə


yükləyin