Python Program for Convert characters of a string to opposite case
Last Updated :
18 Apr, 2025
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:
- Take one string of any length and calculate its length.
- 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
- 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)
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:
- Traverse the given string S.
- For each character, Si, do Si = Si^ (1 << 5).
- Si^ (1 << 5) toggles the 5thbit which means 97 will become 65 and 65 will become 97:
- 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))
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)
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())
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:
- Import the re module, which provides functions for working with regular expressions.
- Define a function that takes a string as an argument.
- Inside the function, define a regular expression pattern that matches any alphabetic character.
- Use the sub() function from the re module to search for the pattern in the string and replace it with a specified replacement string.
- 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.
- Return the modified string.
- 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
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:
- Import the reduce function from functools module
- Initialize a string variable “str” with the value “GeEkSfOrGeEkS”
- 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”
- 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
- Assign the result of the reduce function to a variable called “result”
- 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.
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 :
- Create an empty string result.
- Loop through each character in the input string s.
- If the character is an alphabetic character, toggle its case and append it to result.
- If the character is not an alphabetic character, append it to result.
- 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:
- Initiate a for loop to traverse the string
- Check each character is in upper-ABCDEFGHIJKLMNOPQRSTUVWXYZ if yes add corresponding character in lower- abcdefghijklmnopqrstuvwxyz to output string and viceversa
- 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)
Time Complexity : O(N) N – length of string
Auxiliary Space : O(N) N -length of output string
Similar Reads
Python program to count the number of characters in a String
The goal here is to count the number of characters in a string, which involves determining the total length of the string. For example, given a string like "GeeksForGeeks", we want to calculate how many characters it contains. Letâs explore different approaches to accomplish this. Using len()len() i
3 min read
Python program to remove last N characters from a string
In this article, weâll explore different ways to remove the last N characters from a string in Python. This common string manipulation task can be achieved using slicing, loops, or built-in methods for efficient and flexible solutions. Using String SlicingString slicing is one of the simplest and mo
2 min read
Python program to check a string for specific characters
Here, will check a string for a specific character using different methods using Python. In the below given example a string 's' and char array 'arr', the task is to write a python program to check string s for characters in char array arr. Examples: Input: s = @geeksforgeeks% arr[] = {'o','e','%'}O
4 min read
Python - Convert list of strings and characters to list of characters
Sometimes we come forward to the problem in which we receive a list that consists of strings and characters mixed and the task we need to perform is converting that mixed list to a list consisting entirely of characters. Using itertools.chain()itertools.chain() combines multiple lists or iterables i
3 min read
Python program to convert camel case string to snake case
Camel case is a writing style in which multiple words are concatenated into a single string, Snake case is another writing style where words are separated by underscores (_) and all letters are lowercase. We are going to cover how to convert camel case into snake case. Using Regular Expressions (re.
3 min read
Python Program To Remove all control characters
In the telecommunication and computer domain, control characters are non-printable characters which are a part of the character set. These do not represent any written symbol. They are used in signaling to cause certain effects other than adding symbols to text. Removing these control characters is
3 min read
Python program to count upper and lower case characters without using inbuilt functions
Given a string that contains both upper and lower case characters in it. The task is to count a number of upper and lower case characters in it. Examples :Input : Introduction to Python Output : Lower Case characters : 18 Upper case characters : 2 Input : Welcome to GeeksforGeeks Output : Lower Case
3 min read
Python | Find position of a character in given string
Given a string and a character, our task is to find the first position of the occurrence of the character in the string using Python. For example, consider a string s = "Geeks" and character k = 'e', in the string s, the first occurrence of the character 'e' is at index1. Let's look at various metho
2 min read
Iterate over characters of a string in Python
In this article, we will learn how to iterate over the characters of a string in Python. There are several methods to do this, but we will focus on the most efficient one. The simplest way is to use a loop. Letâs explore this approach. Using for loopThe simplest way to iterate over the characters in
2 min read
Python program to calculate the number of words and characters in the string
We are given a string we need to find the total number of words and total number of character in the given string. For Example we are given a string s = "Geeksforgeeks is best Computer Science Portal" we need to count the total words in the given string and the total characters in the given string.
3 min read