Open In App

Python Program for Convert characters of a string to opposite case

Last Updated : 18 Apr, 2025
Comments
Improve
Suggest changes
Like Article
Like
Report

Given a string, convert the characters of the string into the opposite case,i.e. if a character is the lower case then convert it into upper case and vice-versa. 

Examples: 

Input : geeksForgEeks
Output : GEEKSfORGeEKS

Input: hello every one
Output: HELLO EVERY ONE

Example 1: Python Program for Convert characters of a string to opposite case

ASCII values  of alphabets: A – Z = 65 to 90, a – z = 97 to 122 
Steps: 

  1. Take one string of any length and calculate its length.
  2. Scan string character by character and keep checking the index. 
    • If a character in an index is in lower case, then subtract 32 to convert it in upper case, else add 32 to convert it in lowercase
  3. Print the final string.

Implementation:

Python
# Python3 program to Convert characters
# of a string to opposite case

# Function to convert characters
# of a string to opposite case


def convertOpposite(str):
    ln = len(str)

    # Conversion according to ASCII values
    for i in range(ln):
        if str[i] >= 'a' and str[i] <= 'z':

            # Convert lowercase to uppercase
            str[i] = chr(ord(str[i]) - 32)

        elif str[i] >= 'A' and str[i] <= 'Z':

            # Convert lowercase to uppercase
            str[i] = chr(ord(str[i]) + 32)


# Driver code
if __name__ == "__main__":
    str = "GeEkSfOrGeEkS"
    str = list(str)

    # Calling the Function
    convertOpposite(str)

    str = ''.join(str)
    print(str)

Output
gEeKsFoRgEeKs

Time Complexity: O(n) 
Auxiliary Space: O(n)

Note: This program can alternatively be done using C++ inbuilt functions – Character.toLowerCase(char) and Character.toUpperCase(char). 

Example 2: The problem can be solved using letter case toggling. Follow the below steps to solve the problem:

  1. Traverse the given string S.
  2. For each character, Si, do Si =  Si^ (1 << 5).
  3. Si^ (1 << 5) toggles the 5thbit which means 97 will become 65 and 65 will become 97:
    • 65 ^ 32 = 97
    • 97 ^ 32 = 65 
  4. Print the string after all operations

Below is the implementation of the above approach:

Python
# python program for the same approach
def isalpha(input):
    input_char = ord(input[0])

    # CHECKING FOR ALPHABET
    if((input_char >= 65 and input_char <= 90) or (input_char >= 97 and input_char <= 122)):
        return True
    else:
        return False

# Function to toggle characters


def toggleChars(S):
    s = ""

    for it in range(len(S)):

        if(isalpha(S[it])):
            s += chr(ord(S[it]) ^ (1 << 5))
        else:
            s += S[it]

    return s


# Driver code
S = "GeKf@rGeek$"
print(toggleChars(S))

Output
gEkF@RgEEK$

Time Complexity: O(n)
Auxiliary Space: O(n)

Example 3: Python Program for Convert characters of a string to opposite case

Python
# Python3 program to Convert characters
# of a string to opposite case

str = "GeEkSfOrGeEkS"
x = ""
for i in str:
    if(i.isupper()):
        x += i.lower()
    else:
        x += i.upper()
print(x)

Output
gEeKsFoRgEeKs

Please refer complete article on Convert characters of a string to opposite case for more details!

Example 4: Using swapcase() function

Python
# Python3 program to Convert characters
# of a string to opposite case

str = "GeEkSfOrGeEkS"

print(str.swapcase())

Output
gEeKsFoRgEeKs

Example 5: Convert characters of a string to opposite case Using re

 Here are the steps to convert the characters of a string to the opposite case using the re module and the sub() function:

  1. Import the re module, which provides functions for working with regular expressions.
  2. Define a function that takes a string as an argument.
  3. Inside the function, define a regular expression pattern that matches any alphabetic character.
  4. Use the sub() function from the re module to search for the pattern in the string and replace it with a specified replacement string.
  5. Use a lambda function as the replacement string. The lambda function should take a Match object as an argument and return the opposite case of the matched character. If the character is uppercase, the lambda function should return the character in lowercase. If the character is lowercase, the lambda function should return the character in uppercase.
  6. Return the modified string.
  7. Test the function by calling it with some example strings and printing the output.
Python
import re


def convert_opposite_case(s):
    # Define regular expression pattern for alphabetic characters
    pattern = r'[a-zA-Z]'

    # Replace each character with its opposite case
    s = re.sub(pattern, lambda x: x.group().lower()
               if x.group().isupper() else x.group().upper(), s)

    return s


print(convert_opposite_case('GeEkSfOrGeEkS'))
# This code is contributed by Edula Vinay Kumar Reddy

Output
gEeKsFoRgEeKs

 Time complexity: O(n) because it involves a single call to the re.sub() function, which has a time complexity of O(n). The re.sub() function iterates through all the characters in the input string and applies the provided replacement function to each character.
Auxiliary Space: O(n) because it involves creating a new string with the same length as the input string. 

Examoke 6: Using reduce() function and lambda expression

Algorithm:

  1. Import the reduce function from functools module
  2. Initialize a string variable “str” with the value “GeEkSfOrGeEkS”
  3. Define a lambda function that takes two arguments “x” and “y” and returns the concatenation of “x” and the lowercase version of “y” if “y” is an uppercase character, else returns the concatenation of “x” and the uppercase version of “y”
  4. Use the reduce function to apply the lambda function to each character in the string “str”, starting with an empty string as the initial value
  5. Assign the result of the reduce function to a variable called “result”
  6. Print the value of “result”, which should be the converted string “gEeKsFoRgEeKs”
Python
from functools import reduce
str = "GeEkSfOrGeEkS"
result = reduce(lambda x, y: x+y.lower() if y.isupper()
                else x+y.upper(), str, "")
print(result)

# This code is contributed by Rayudu.

Output
gEeKsFoRgEeKs

Time complexity: O(n)
where n is the length of the input string. This is because we are traversing the string only once using reduce().

 Auxiliary space: O(n)
As we are creating a new string of the same length as the input string.

Example 7: Convert characters of a string to opposite case Using numpy:

Algorithm :

  1. Create an empty string result.
  2. Loop through each character in the input string s.
  3. If the character is an alphabetic character, toggle its case and append it to result.
  4. If the character is not an alphabetic character, append it to result.
  5. Return the result string.
Python
import numpy as np

def convert_opposite_case(s):
# Create a NumPy array from the string
   arr = np.frombuffer(s.encode('utf-8'), dtype='uint8').copy()

# Find the indices of the alphabetic characters
   idx = np.where(np.logical_or(arr >= 65, arr <= 122))[0]

# Toggle the case of each alphabetic character
   arr[idx] ^= 32

# Convert the NumPy array back to a string
   return arr.tobytes().decode('utf-8')

print(convert_opposite_case('GeEkSfOrGeEkS'))
#This code  is contributed Jyothi pinjala

Output:

gEeKsFoRgEeKs

Time Complexity:
The isupper and islower methods used to check the case of each alphabetic character have a time complexity of O(1).
Therefore, the time complexity of this algorithm is O(n), where n is the length of the input string s.

Auxiliary Space: 
The space required for the result string is O(n), where n is the length of the input string s.
Therefore, the auxiliary space of this algorithm is also O(n).

Example 8 : Using index(),without upper() and lower() methods

Approach:

  1. Initiate a for loop to traverse the string
  2. Check each character is in upper-ABCDEFGHIJKLMNOPQRSTUVWXYZ if yes add corresponding character in lower- abcdefghijklmnopqrstuvwxyz to output string and viceversa
  3. Display output string
Python
# Python3 program to Convert characters
# of a string to opposite case

str = "GeEkSfOrGeEkS"
x = ""
lower="abcdefghijklmnopqrstuvwxyz"
upper="ABCDEFGHIJKLMNOPQRSTUVWXYZ"
for i in str:
    if(i in upper):
        x += lower[upper.index(i)]
    elif(i in lower):
        x += upper[lower.index(i)]
print(x)

Output
gEeKsFoRgEeKs

Time Complexity : O(N) N – length of string
Auxiliary Space : O(N) N -length of output string



Next Article
Practice Tags :

Similar Reads