Python Program to Swap String Case Without Using swapcase()

By | November 29, 2024

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
Author: Mithlesh Upadhyay

Mithlesh Upadhyay is a Computer Science and AI expert from Madhya Pradesh with strong academic background (BE in CSE and M.Tech in AI) and over six years of experience in technical content development. He has contributed tech articles, led teams, and worked in Full Stack Development and Data Science. He founded the w3colleges.org portal for learning resources.