Python Program for Convert characters of a string to opposite case
Last Updated :
27 Jul, 2023
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:
Python3
def convertOpposite( str ):
ln = len ( str )
for i in range (ln):
if str [i] > = 'a' and str [i] < = 'z' :
str [i] = chr ( ord ( str [i]) - 32 )
elif str [i] > = 'A' and str [i] < = 'Z' :
str [i] = chr ( ord ( str [i]) + 32 )
if __name__ = = "__main__" :
str = "GeEkSfOrGeEkS"
str = list ( str )
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 5th bit which means 97 will become 65 and 65 will become 97:
- 65 ^ 32 = 97
- 97 ^ 32 = 65
- Print the string after all operations
Below is the implementation of the above approach:
Python3
def isalpha( input ):
input_char = ord ( input [ 0 ])
if ((input_char > = 65 and input_char < = 90 ) or (input_char > = 97 and input_char < = 122 )):
return True
else :
return False
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
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
Python3
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
Python3
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.
Python3
import re
def convert_opposite_case(s):
pattern = r '[a-zA-Z]'
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' ))
|
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”
Python3
from functools import reduce
str = "GeEkSfOrGeEkS"
result = reduce ( lambda x, y: x + y.lower() if y.isupper()
else x + y.upper(), str , "")
print (result)
|
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.
Python3
import numpy as np
def convert_opposite_case(s):
arr = np.frombuffer(s.encode( 'utf-8' ), dtype = 'uint8' ).copy()
idx = np.where(np.logical_or(arr > = 65 , arr < = 122 ))[ 0 ]
arr[idx] ^ = 32
return arr.tobytes().decode( 'utf-8' )
print (convert_opposite_case( 'GeEkSfOrGeEkS' ))
|
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
Python3
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
Like Article
Suggest improvement
Share your thoughts in the comments
Please Login to comment...