Python-courses-python-exercises-python-exception-python-pip

Exercise 55

Write a python program as a function which takes as parameters a string s 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 swapcase() method. Example if s = "Hello Wordls!" , the function returns the string "hELLO wORLD!"

Solution

def mySwapcase(s):

# initializing the swapped string
s_swap = ""

# iterate over all characters of s
#and testing if the character is in uppercase or lowercase
for x in s:
if x.isupper():

# swapping the character
x = x.lower()
s_swap = s_swap + x
elif x.islower():
# swapping the character
x = x.upper()
s_swap = s_swap + x
else:
s_swap = s_swap + x

return s_swap

# test and display result
print(mySwapcase("Hello World !")) # The output is : hELLO wORLD !

Younes Derfoufi
my-courses.net

Leave a Reply