
Data Structure
Networking
RDBMS
Operating System
Java
MS Excel
iOS
HTML
CSS
Android
Python
C Programming
C++
C#
MongoDB
MySQL
Javascript
PHP
- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who
Convert Characters of a String to Opposite Case in Python
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() method to change the case.
Here, we will learn different approaches to solving the problem.
Problem statement - We have given a string alpha. 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 = "AAAA"
Output
'aaaa'
Input
alpha = '12qwER@'
Output
'12QWer@'
Explanation - We changed the case of each alphabetical character and kept special characters as it is.
Approach 1
In this approach, we add 32 to the ASCII value of the character if the character is in uppercase. Otherwise, we subtract the 32 from the ASCII value of the character to convert the character to uppercase.
Algorithm
Step 1 - Convert the string to the 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 of the character, and update the character in the list.
Step 4 - If the character is between 'a' to 'z', subtract the 32 from the character's ASCII value and update the character in the list.
Step 5 - Use the join() method to convert all characters of the list into the string.
Step 6 - Return the resultant 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" alpha = changeCase(alpha) print("The string after flipping the case of each character is -", alpha)
Output
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.
Approach 2
In this approach, we use the isUpper() method to check whether the character is in uppercase. Also, we use the upper() and lower() methods to convert the character to uppercase and lowercase, respectively.
Algorithm
Step 1 - Initialize the 'temp' with an empty string to store the resultant string.
Step 2 - Iterate the string.
Step 3 - If a character is in uppercase, use the lower() method to convert the character into lowercase and append it to the temp string.
Step 4 - Otherwise, use the upper() method to convert the character to uppercase and append it to the temp string.
Step 5 - Return the 'temp' string.
Example
def changeCase(alpha): temp = "" for ch in alpha: # Using the isupper() method to check if the character is uppercase or not if (ch.isupper()): # Converting a character to lowercase temp += ch.lower() else: temp += ch.upper() # Converting a character to uppercase return temp alpha = "TutorialsPoint" alpha = changeCase(alpha) print("The string after flipping the case of each character is -", alpha)
Output
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.
Approach 3
In this approach, we use the swapcase() method to toggle the case of the character. We stored the alpha string to itself after toggling the case of each character.
Example
def changeCase(alpha): # Using the swapcase() function to toggle the case of characters of the string alpha = alpha.swapcase() return alpha alpha = "AbcSDe" alpha = changeCase(alpha) print("The string after flipping the case of each character is -", alpha)
Output
The string after flipping the case of each character is - aBCsdE
Time complexity - O(N)
Space complexity - O(1)
Approach 4
In this approach, we will use the regular expression and lambda function to toggle the case of each string character.
Algorithm
Step 1 - Initialize the 'patt' to search for the lowercase and uppercase alphabetical characters.
Step 2 - Next, use the re.sub() method to replace all alphabetical characters with their opposite case.
Step 3 - Use the 'patt' as the first parameter of the sub() method, the lambda function to toggle the character as a second parameter, and the original string as a third parameter.
Step 4 - Return the alpha string.
Example
import re def changeCase(alpha): # Regular expression patt = r'[a-zA-Z]' # Toggle case of each character alpha = re.sub(patt, lambda ch: ch.group().lower() if ch.group().isupper() else ch.group().upper(), alpha) return alpha alpha = "TutorialsPoint" alpha = changeCase(alpha) print("The string after flipping the case of each character is -", alpha)
Output
The string after flipping the case of each character is - tUTORIALSpOINT
Time complexity - O(N)
Space complexity - O(1)
Approach 5
In this approach, we will perform the XOR operation of the ASCII value of the character with the 32 to toggle the case.
When we take XOR of 32 with any alphabetical character, it toggles the 6th bit of the binary representation of the ASCII value.
Let's understand it via the example below.
65 = 'A' = 1000001
97 = 'a' = 1100001
32 = 0100000
So, when we take the XOR of 65 and 32, it becomes 97 as the 6th bit gets flipped, and similarly, the XOR of 97 and 32 becomes 32.
This will work for all ASCII values of the alphabetical characters.
Algorithm
Step 1 - Start traversing the string.
Step 2 - Execute the isAlphabeticChar() function to check whether the current character is alphabetical.
Step 3 - In the isAlphabeticChar() function, return true if the ASCII value is between 65 and 90 or 97 and 122. Otherwise, return false.
Step 4 - If the current character is an alphabetical character, take its XOR with 32, and append the updated character to the 'temp' string.
Step 5 - Otherwise, append the original character to the temp string.
Step 6 - Return the temp string.
Example
def isAlphbeticChar(char): Ascii = ord(char[0]) # Using ASCII values to validate character if((Ascii >= 65 and Ascii <= 90) or (Ascii >= 97 and Ascii <= 122)): return True else: return False def changeCase(alpha): temp = "" for ch in range(len(alpha)): if(isAlphbeticChar(alpha[ch])): temp += chr(ord(alpha[ch]) ^ (1 << 5)) else: temp += alpha[ch] return temp alpha = "TutorialsPoint" alpha = changeCase(alpha) print("The string after flipping the case of each character is -", alpha)
Output
The string after flipping the case of each character is - tUTORIALSpOINT
Time complexity - O(N)
Space complexity - O(N)
We learned 5 approaches to toggle each character of the string. The first approach uses the ASCII value, and the second approach uses the isUpper(), upper(), and lower() methods.
Furthermore, the third approach uses the swapcase() method, the fourth approach uses the regular expression, and the last approach uses the XOR operator.