
Swap Case in Python - Hacker Rank Challenge to Write a Function that swaps the case of all letters in a string
Apr 23
1 min read
0
2
0

Suppose you were given a string that was equal to:
Hello - Welcome To The Python Community but you needed it to return:
hELLO - wELCOME tO tHE pYTHON cOMMUNITY.
How would you do it?
This is precisely the problem that Hacker Rank has presented us with today.
The code solution is below.
The first thing to do is to create an empty list.
Next, loop through all of the letters in the given string.
For each letter - if it is lowercase make it upper case, if it is uppercase make it lowercase.
Write the values to a new list.
Concatenate the list into a string
And,
Finally return the result.
def swap_case(s):
   new_string = []
   for letter in s:
       if letter.isupper() == True:
           letter = letter.lower()
       elif letter.islower() == True:
           letter = letter.upper()
       new_string.append(letter)
   #print(new_string)
   a_string = ''.join(new_string)
   return(a_string)
Â
if name == '__main__':
   s = input()
   result = swap_case(s)
   print(result)