By using the (Exercise 51), create a python algorithm as a function that takes as input a string s and which returns the same string in lowercase without using the lower() method. You can use the chr() and ord() methods.
def toLowercase(s): # Based on the exercise 51 we can obtain the lists of all upercase characters and lowercase characters: uppercase_characters = [chr(i) for i in range(65 , 91)] lowercase_characters = [chr(i) for i in range(97 , 122)] # then we can obtain a lowercase characters from uppercase characters by adding 32 to its ascii code # initializing the searched string s_lower = "" for x in s: if x in uppercase_characters: x = chr(ord(x) + 32) s_lower = s_lower + x else : s_lower = s_lower + x return s_lower print(toLowercase("PYTHON Programming")) # The output is : 'python programming'
In this algorithm:
- The list [chr(i) for i in range(65 , 91)]: used to generate the list of all uppercase charachter [A, B, ..., Z]
- The list [chr(i) for i in range(97 , 122)]: used to generate the list of all lowercase charachter [a, b, ..., z]
- s_lower = "": is the seached string initialized to the empty string.
- for x in s: used to iterate over all charachter in the string s.
- Then we test if the charchter 'x' is in the uppercase_characters list: we transform it into lowercase by using the chr() and ord() method, and then we add it into the s_lower string s.
- If the charchter 'x' is in the lowercase_characters list: we add it into the s_lower string.
1 thought on “Solution Exercise 53 : python program which transform given a string into lowercase”