Python swapcase without using Swapcase()

parksontano

Daniel Parkson Tano

Posted on December 26, 2022

Python swapcase without using Swapcase()

We can easily swap the cases of characters in string using the python inbuilt swapcase() function.
Casing swapping is simply changing upper case character to lower case character and lower case character to upper case character.
For example:
If we swap case the string "helloWorld" we will get "HELLOwORLD".

Example of using python swapcase()

Swap the cases in the string "Welcome to Tano Space".

string = "python IS A PROGRAMMING language"
new_string = swapcase(string)
print(new_string)
//it will return "PYTHON is a programming LANGUAGE"
Enter fullscreen mode Exit fullscreen mode

It's simple right? Yes. But assuming you are in a technical interview for a python developer role, and the interviewer asked you to write a python thats swap the cases of characters in a string. You can't use the swapcase() function. How then will you be able to achieve such ?
The code below depict one of the ways to write the code.

Let me show you how

string = "python IS A PROGRAMMING language"
 new_string = []

for i in string:
    #check if the character is a upper case letter
    if i.isupper():
        #if the character is upper case the change it to lower 
        #case 
        i.lower()
        # add the converted character to the list
        new_string.append(i)
    else:
        i.upper()
        new_string.append(i)

#use the join() to combine the items of the list
print("".join(new_string)
Enter fullscreen mode Exit fullscreen mode

You are Welcome

💖 đŸ’Ē 🙅 🚩
parksontano
Daniel Parkson Tano

Posted on December 26, 2022

Join Our Newsletter. No Spam, Only the good stuff.

Sign up to receive the latest update from our blog.

Related