P ython p rogramming e xercises


Exercise #10: Find and Replace



Yüklə 1,51 Mb.
Pdf görüntüsü
səhifə112/124
tarix14.05.2023
ölçüsü1,51 Mb.
#113537
1   ...   108   109   110   111   112   113   114   115   ...   124
PythonProgrammingExercisesGentlyExplained

Exercise #10: Find and Replace 
def findAndReplace(text, oldText, newText): 
replacedText = '' 
i = 0 
while i < len(text): 
# If index i in text is the start of the oldText pattern, add 
# the replacement text: 
if text[i:i + len(oldText)] == oldText: 
# Add the replacement text: 
replacedText += newText 
# Increment i by the length of oldText: 
i += len(oldText) 
# Otherwise, add the characters at text[i] and increment i by 1: 
else: 
replacedText += text[i] 
i += 1 
return replacedText 
Exercise #11: Hours, Minutes, Seconds 
def getHoursMinutesSeconds(totalSeconds): 
# If totalSeconds is 0, just return '0s': 
if totalSeconds == 0: 
return '0s' 
# Set hours to 0, then add an hour for every 3600 seconds removed from 
# totalSeconds until totalSeconds is less than 3600: 
hours = 0 
while totalSeconds >= 3600: 
hours += 1 
totalSeconds -= 3600 
# Set minutes to 0, then add a minute for every 60 seconds removed from 


Python Programming Exercises, Gently Explained 
138 
# totalSeconds until totalSeconds is less than 60: 
minutes = 0 
while totalSeconds >= 60: 
minutes += 1 
totalSeconds -= 60 
# Set seconds to the remaining totalSeconds value: 
seconds = totalSeconds 
# Create an hms list that contains the string hour/minute/second amounts: 
hms = [] 
# If there are one or more hours, add the amount with an 'h' suffix: 
if hours > 0: 
hms.append(str(hours) + 'h') 
# If there are one or more minutes, add the amount with an 'm' suffix: 
if minutes > 0: 
hms.append(str(minutes) + 'm') 
# If there are one or more seconds, add the amount with an 's' suffix: 
if seconds > 0: 
hms.append(str(seconds) + 's') 
# Join the hour/minute/second strings with a space in between them: 
return ' '.join(hms) 

Yüklə 1,51 Mb.

Dostları ilə paylaş:
1   ...   108   109   110   111   112   113   114   115   ...   124




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

gir | qeydiyyatdan keç
    Ana səhifə


yükləyin