Generally, we use swapcase() to swap strings in Python. What if we are asked to do swapping without using the method. In this article, I will be sharing python program to swap upper case letters to lower case and vice versa in the same string.
Examples:
Input: "w3ColLeges" Output: "W3cOLlEGES" Input: "W3cOlLegEs OrG" Output: "w3CoLlEgEs oRg"
Some letters are in lower case while some are in uppercase, the below program will change lower case letters to uppercase ansd uppercase letters to lowercase. Unlike upper() or lower() which change all characters in the to other case whether they are upper case or lower case.
Basically, this will be the algorithm for swapcase() method.
Here it goes like this:
# Python program to change case in string without using Swapcase()
string = 'I gOT chANgeD'
# A new string after coversion
newString = ""
# Iterating through all letters in string
for i in range(len(string)):
if string[i].isupper(): # checking if a letter is uppercase
newString += string[i].lower()
else:
newString += string[i].upper()
print(newString)
Output
i Got CHanGEd
