Exercise 55
Write a python program as a function which takes a string s as input and which returns a string obtained from the string s by transforming each uppercase character into a lowercase character and vice versa without using the built-in swapcase() method. Example: if s = "Hello Wordls!" , the function returns the string s = "hELLO wORLD!"
Solution
def swap_case(s): swapped = "" for letter in s: if letter.isupper(): swapped += letter.lower() else: swapped += letter.upper() return swapped s = "Hello Wordls!" swapped = swap_case(s) print(swapped) # Output: hELLO wORLD!
Explanation:
- This function takes in a single parameter s: which is the input string to be transformed.
- It creates an empty string 'swapped': and then iterates over each character in the input string.
- For each character: it checks whether it is uppercase or not using the isupper() method.
- If it is uppercase: it appends the lowercase version of the letter to the swapped string, otherwise it appends the uppercase version of the letter.
- The function returns the swapped string: which contains the transformed version of the input string.
- Finally we test the function by the input string s is "Hello Wordls!": and the swap_case function is called with this string as a parameter.
- The returned string swapped: is then printed to the console, which produces the output "hELLO wORLD!".
Younes Derfoufi
my-courses.net
[…] Exercise 55 ** || Solution […]