Python
Programming Exercises, Gently Explained
148
# Loop over all the characters in text, adding non-lowercase
# characters to our new string:
for character in text:
if character in LOWER_TO_UPPER:
# Append the uppercase form to the new string:
uppercaseText += LOWER_TO_UPPER[character]
else:
uppercaseText +=
character
# Return the uppercase string:
return uppercaseText
Exercise #35: Title Case
def getTitleCase(text):
# Create a titledText variable to store the titlecase text:
titledText = ''
# Loop over every index in text:
for i in range(len(text)):
# The character at the start of text should be uppercase:
if i == 0:
titledText += text[i].upper()
# If the character is a letter and the previous character is
# not a letter, make it uppercase:
elif text[i].isalpha() and not text[i - 1].isalpha():
titledText += text[i].upper()
# Otherwise, make it lowercase:
else:
titledText += text[i].lower()
# Return the titled cased string:
return titledText
Exercise #36: Reverse String
def reverseString(text):
# Convert the text string into a list of character strings:
text = list(text)
# Loop over the first half of indexes in the list:
for i in range(len(text) // 2):
# Swap the values of i and it's mirror index in the second
# half of the list:
mirrorIndex = len(text) - 1 - i
text[i], text[mirrorIndex] = text[mirrorIndex], text[i]
# Join the list of strings into a single string and return it:
return ''.join(text)
Dostları ilə paylaş: