swap case

 avatar
unknown
python
4 years ago
1.9 kB
11
Indexable
'''
You are given a string and your task is to swap cases. In other words, convert all lowercase letters to uppercase letters and vice versa.

Sample Input 0
HackerRank.com presents "Pythonist 2".

Sample Output 0
hACKERrANK.COM PRESENTS "pYTHONIST 2".
'''

'''
My Algo:
1. Create an empty list for appending the output
2. Iterate throught the given string
  i. Check if the char is alphabet
    i. If alphabet then check if lower case and convert to upper case and append to the empty list
    ii. If alphabet then check if upper case and convert to lower case and append to the empty list
  ii. If the char is not an alphabet just append it to the empty list as it is
3. Join back the list and convert to a string and return
'''

def swap_case(s):
    # create empty list for appending the case switched letters and non-alphabetic characters too
    swapped_string_list = []
    
    # iterate through the string
    for char in range(len(s)):
        # if the char is alphabet
        if s[char].isalpha():
            # if the alphabet is in lower case
            if s[char].islower():
                # convert to upper case and append to the empty list
                swapped_string_list.append(s[char].upper())
            # if the alphabet is upper case
            if s[char].isupper():
                # convert to lower case and append to the empty list
                swapped_string_list.append(s[char].lower())
        # if the char is not alphabet then just append to the empty list as it is
        else:
            swapped_string_list.append(s[char])
    # join back the list and convert to string and return
    return ''.join(swapped_string_list)

if __name__ == '__main__':
    s = input()
    # s = 'HackerRank.com presents "Pythonist 2".'
    result = swap_case(s)
    print(result)
Editor is loading...