P ython p rogramming e xercises


Exercise #34: Uppercase Letters



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

Exercise #34: Uppercase Letters 
# Map the lowercase letters to uppercase letters. 
LOWER_TO_UPPER = {'a': 'A', 'b': 'B', 'c': 'C', 'd': 'D', 'e': 'E', 'f': 'F', 'g': 
'G', 'h': 'H', 'i': 'I', 'j': 'J', 'k': 'K', 'l': 'L', 'm': 'M', 'n': 'N', 'o': 'O', 
'p': 'P', 'q': 'Q', 'r': 'R', 's': 'S', 't': 'T', 'u': 'U', 'v': 'V', 'w': 'W', 'x': 
'X', 'y': 'Y', 'z': 'Z'} 
def getUppercase(text): 
# Create a new variable that starts as a blank string and will 
# hold the uppercase form of text: 
uppercaseText = '' 


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) 

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 2024
rəhbərliyinə müraciət

gir | qeydiyyatdan keç
    Ana səhifə


yükləyin