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:

  1. This function takes in a single parameter s: which is the input string to be transformed.
  2. It creates an empty string 'swapped': and then iterates over each character in the input string.
  3. For each character: it checks whether it is uppercase or not using the isupper() method.
  4. 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.
  5. The function returns the swapped string: which contains the transformed version of the input string.
  6. 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.
  7. The returned string swapped: is then printed to the console, which produces the output "hELLO wORLD!".

 

Younes Derfoufi
my-courses.net

One thought on “Solution Exercise 55: Python algorithm to swap a given string without using the swapcase method”

Leave a Reply