Article Categories
- All Categories
-
Data Structure
-
Networking
-
RDBMS
-
Operating System
-
Java
-
MS Excel
-
iOS
-
HTML
-
CSS
-
Android
-
Python
-
C Programming
-
C++
-
C#
-
MongoDB
-
MySQL
-
Javascript
-
PHP
-
Economics & Finance
Python Program for Convert characters of a string to opposite case
In this problem, we will toggle the case of each string character. The easiest way to toggle the case of each string character is using the swapcase() built-in method.
Also, we can use the ASCII values of the characters to swap their case. Python also contains isupper() and islower() methods to check the character's case and the lower() and upper() methods to change the case.
Problem statement We have given a string. We need to toggle the case of string characters. It means converting uppercase characters to lowercase and lowercase characters to uppercase.
Sample Examples
Input
alpha = "TutorialsPoint"
Output
'tUTORIALSpOINT'
Explanation Here, we have toggled the case of each character.
Input
alpha = '12qwER@'
Output
'12QWer@'
Explanation We changed the case of each alphabetical character and kept special characters as they are.
Using ASCII Values
In this approach, we add 32 to the ASCII value if the character is uppercase. Otherwise, we subtract 32 from the ASCII value to convert it to uppercase ?
Algorithm
Step 1 Convert the string to a list of characters.
Step 2 Traverse the list of characters.
Step 3 If the character is between 'A' to 'Z', add 32 to the ASCII value.
Step 4 If the character is between 'a' to 'z', subtract 32 from the ASCII value.
Step 5 Use the join() method to convert the list back to a string.
Example
def changeCase(alpha):
alpha_list = list(alpha) # String to list
# Traverse list of string characters
for p in range(len(alpha_list)):
if alpha_list[p] >= 'A' and alpha_list[p] <= 'Z':
alpha_list[p] = chr(ord(alpha_list[p]) + 32) # Change to lowercase
elif alpha_list[p] >= 'a' and alpha_list[p] <= 'z':
alpha_list[p] = chr(ord(alpha_list[p]) - 32) # Change to uppercase
alpha = ''.join(alpha_list) # List to string
return alpha
alpha = "TutorialsPoint"
result = changeCase(alpha)
print("The string after flipping the case of each character is -", result)
The string after flipping the case of each character is - tUTORIALSpOINT
Time complexity O(N) to traverse the string characters.
Space complexity O(N) to store the string in the list of characters.
Using isupper() and Case Methods
In this approach, we use the isupper() method to check whether the character is uppercase. We use the upper() and lower() methods to convert the character accordingly ?
Example
def changeCase(alpha):
temp = ""
for ch in alpha:
# Using the isupper() method to check if character is uppercase
if ch.isupper():
# Converting character to lowercase
temp += ch.lower()
else:
temp += ch.upper() # Converting character to uppercase
return temp
alpha = "TutorialsPoint"
result = changeCase(alpha)
print("The string after flipping the case of each character is -", result)
The string after flipping the case of each character is - tUTORIALSpOINT
Time complexity O(N) for traversing the string.
Space complexity O(N) to store the resultant string.
Using swapcase() Method
The swapcase() method is the built-in Python method that directly toggles the case of all characters in a string ?
Example
def changeCase(alpha):
# Using the swapcase() function to toggle the case of characters
return alpha.swapcase()
alpha = "AbcSDe"
result = changeCase(alpha)
print("The string after flipping the case of each character is -", result)
The string after flipping the case of each character is - aBCsdE
Time complexity O(N)
Space complexity O(1)
Using Regular Expression
In this approach, we use regular expressions and lambda functions to toggle the case of each string character ?
Example
import re
def changeCase(alpha):
# Regular expression pattern to match alphabetical characters
patt = r'[a-zA-Z]'
# Toggle case of each character using lambda function
alpha = re.sub(patt, lambda ch: ch.group().lower()
if ch.group().isupper() else ch.group().upper(), alpha)
return alpha
alpha = "TutorialsPoint"
result = changeCase(alpha)
print("The string after flipping the case of each character is -", result)
The string after flipping the case of each character is - tUTORIALSpOINT
Time complexity O(N)
Space complexity O(1)
Using XOR Operation
In this approach, we perform the XOR operation of the ASCII value with 32 to toggle the case. When we XOR 32 with any alphabetical character, it toggles the 6th bit of the binary representation ?
For example:
65 = 'A' = 1000001
97 = 'a' = 1100001
32 = 0100000
When we XOR 65 and 32, it becomes 97 as the 6th bit gets flipped.
Example
def isAlphabeticChar(char):
ascii_val = ord(char)
# Using ASCII values to validate character
if (ascii_val >= 65 and ascii_val <= 90) or (ascii_val >= 97 and ascii_val <= 122):
return True
else:
return False
def changeCase(alpha):
temp = ""
for ch in alpha:
if isAlphabeticChar(ch):
temp += chr(ord(ch) ^ (1 << 5)) # XOR with 32 (which is 1<<5)
else:
temp += ch
return temp
alpha = "TutorialsPoint"
result = changeCase(alpha)
print("The string after flipping the case of each character is -", result)
The string after flipping the case of each character is - tUTORIALSpOINT
Time complexity O(N)
Space complexity O(N)
Comparison
| Method | Time Complexity | Space Complexity | Best For |
|---|---|---|---|
| ASCII Values | O(N) | O(N) | Understanding ASCII manipulation |
| isupper() Methods | O(N) | O(N) | Readable code |
| swapcase() | O(N) | O(1) | Simplest and most efficient |
| Regular Expression | O(N) | O(1) | Complex pattern matching |
| XOR Operation | O(N) | O(N) | Bitwise operation practice |
Conclusion
The swapcase() method is the most efficient and readable approach for toggling character case. For learning purposes, the ASCII manipulation and XOR approaches help understand low-level string operations.
