Exercise 52
Using (Exercise 51), write a python program as a function which takes a string s as input and returns the same string in uppercase without using the upper() method. You can use the chr() and ord() methods.
Solution
def uppercase_string(s): result = "" for letter in s: if 97 <= ord(letter) <= 122: # check if letter is lowercase result += chr(ord(letter) - 32) # convert to uppercase and append to result else: result += letter # if not lowercase, simply append to result return result # Example s = 'Python programming' print(uppercase_string(s)) # output: 'PYTHON PROGRAMMING'
Explanation:
- This function takes a string s: as input and returns the uppercase version of the same string without using the built-in upper() method.
- The function works by iterating: over each character in the string and checking whether it is a lowercase letter (which have ASCII codes between 97 and 122).
- If the character is a lowercase letter: the function subtracts 32 from its ASCII code (which converts it to the corresponding uppercase letter) using chr() and appends it to the result string.
- If the character is not a lowercase letter: it is simply appended to the result string as is.
- Finally: the function returns the result string.
Younes Derfoufi
my-courses.net
[…] Exercise 52 * || Solution […]