Skip to content Skip to sidebar Skip to footer

Swap Cases In A String

I'm trying to solve this challenge in hackerrank, which asks to convert all lowercase letters to uppercase letters and vice versa. I attempt it with the following code: def swap_c

Solution 1:

The built-in str.swapcase already does this.

defswap_case(s):
    return s.swapcase()

Solution 2:

As said in comments and othe answers, strings are immutable.

Try following:

s = input("Enter input: ")


defconvert(ss):
    # Convert it into list and then change it
    newSS = list(ss)
    for i,c inenumerate(newSS):
        newSS[i] = c.upper() if c.islower() else c.lower()
    # Convert list back to stringreturn''.join(newSS)

print(s)
print(convert(s))

# Or use string build in methodprint (s.swapcase())

Solution 3:

defswap_case(s):
    new = ""for i inrange(len(s)):
        ifstr.isupper(s[i]):
            new = new + str.lower(s[i])

        elifstr.islower(s[i]):
            new = new + str.upper(s[i])

        else:
            new = new + str(s[i])
        
    return (new)

if __name__ == '__main__':
    s = input()
    result = swap_case(s)
    print(result)

Solution 4:

As @Julien stated in comment upper and lower methods return a copy, and do not change the object itself. See this docs.

EDIT @aryamccarthy reminded me of already existing feature for this kind of task in python: swapcase() method. See more here. Note this also returns a copy of the string.

Solution 5:

Python-3 in-built swapcase function.

defswap_case(s):
    return s.swapcase()

if __name__ == '__main__':
    s = input()
    result = swap_case(s)
    print(result)

Input:

"Pythonist 3"

Output:

"pYTHONIST 3"

Post a Comment for "Swap Cases In A String"