How do I create while loop the swaps all lower case letters in. string to upper case and vicevera?

Viewed 324
def swap_case(string):
    pos = 0
    while pos < len(string):
        if string[pos].isupper():
            return string[pos].lower()
        else:
            return string[pos].upper()
        pos = pos + 1

print(swap_case('Hello'))

This what I've attempted however it only converts the first letter and no other letters within the inputed string, is anyone able to help me understand how to correctly write this code. I'm a beginner.

1 Answers

The bug in your code is that the return statement is too soon after the first iteration, that's why only the first letter is returned.

The use of 'string' as a variable is discouraged because it is a reserved word, for example

import string
letters = list(string.ascii_lowercase)

I have also converted the string s to a list ['H', 'e', 'l', 'l', 'o'], so that each letter can be iterated through to check/change the case.

Finally the converted list can be returned with ''.join(s)

def swap_case(s):
    pos = 0
    s = list(s)
    while pos < len(s):
        if s[pos].isupper():
            s[pos] = s[pos].lower()
        else:
            s[pos] = s[pos].upper()
        pos = pos + 1
    return ''.join(s)

print(swap_case('Hello'))

Output

hELLO

Another way is to use list comprehension, same output as above

def swap_case(s):
    return ''.join([x.lower() if x.isupper() else x.upper() for x in list(s)])

print(swap_case('Hello'))
Related