Out of curiosity, how would you reverse a string's case in Python? Make uppercase characters lowercase and lowercase characters uppercase.

Here's the function for the naive implementation.

#!/usr/bin/env python

def flip_case(input_string):
    temp_list = list(input_string)
    for index, character in enumerate(temp_list):
        if character.islower():
            temp_list[index] = character.upper()
        else:
            temp_list[index] = character.lower()
    output_string = ''.join(temp_list)
    return output_string

my_string = "AaBbCc"

my_string = flip_case(my_string)

print(my_string)

The output is:

aAbBcC

I'm thinking a smarter implementation would be to use a string's translate method. What do you think?

I would use the re module and substitution

import re
pattern = re.compile(r"([a-z]+)|[A-Z]+")

def swap(match):
  return match.group(0).upper() if match.group(1) else match.group(0).lower()

def swapcase(msg):
    return pattern.sub(swap, msg)

if __name__ == "__main__":
    print (swapcase("HellO WOrlD!"))

""" my output --->
hELLo woRLd!
"""

Edited 7 Years Ago by Gribouillis: n/a

Isnt this allready a method of string?

>>> x = 'Testing ONE TWO THREE'
>>> x.swapcase()
'tESTING one two three'
>>>
Comments
Very knowledgeable.
good point

Isnt this allready a method of string?

>>> x = 'Testing ONE TWO THREE'
>>> x.swapcase()
'tESTING one two three'
>>>

Excellent remark. It's the best method ;)

Strange how I missed that even after looking at the Python documentation for strings.

Strange how I missed that even after looking at the Python documentation for strings.

Type help(str) in a python console.

This question has already been answered. Start a new discussion instead.