Skip to content Skip to sidebar Skip to footer

Swapping String Case In Python

I'm rank new in Python, thus the question, I'm trying to solve a simple problem, where the program takes in a simple string and swaps all the cases. Thus if we enter SimPLE We sho

Solution 1:

As a generator expression:

mystr = "SimPLE"print("".join(c.upper() if c.islower() else c.lower() for c in mystr))

The breakdown of the above is:

c.upper() if c.islower() else c.lower()

is an conditional expression that will convert a character from upper to lower case and vice versa.

Then,

(... forcin mystr)

is a generator expression, which is somewhat like a list that is generated on-the-fly.

Finally:

".join(...)

will join any sequence of strings together with nothing ("") between them.

Solution 2:

Do this in one fell swoop with a string join on a list comprehension of individual characters:

outstr = ''.join([s.upper() if s.islower() else s.lower() for s in oldStr])
print(outstr)

Input & Output:

sIMple
SimPLE

Solution 3:

Strings are immutable. What this means is that when you use the function s.upper(), it is not setting that letter in str to be uppercase, it simply returns that letter in uppercase.

Here is some code that works:

def main():
    oldStr = input()
    newStr = ""
    for s in oldStr:
        if s.islower():
            newStr+=s.upper()
        elif s.isupper():
            newStr+=s.lower()
    print(newStr)

Notice now that we are creating a new string and simply adding the letters at each point in the forloop as opposed to changing those letters in str.

Solution 4:

You are running each character through lower() and upper(), but these functions do not change the character.

Instead, they return the modified version of the character. The original character s will stay as it is.

You should build a new string based off the return values of lower() and upper(), and return that string.

Solution 5:

1) you need to put the main() call on new line, as python relies on whitespace heavily for program structure

2) s is a temporary variable created for the purpose of the for statement. It doesn't actually reference the character in the string

Essentially what is going on is that s has the same value as the character in the string, but it IS NOT ACTUALLY the character in the string.

Post a Comment for "Swapping String Case In Python"