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?

Recommended Answers

All 6 Replies

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!
"""

Isnt this allready a method of string?

>>> x = 'Testing ONE TWO THREE'
>>> x.swapcase()
'tESTING one two three'
>>>
commented: good point +2
commented: Very knowledgeable. +1

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.

Im glad I could be Capt Obvious :D

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.