DEV Community

Cover image for Python swapcase without using Swapcase()
Daniel Parkson Tano
Daniel Parkson Tano

Posted on

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

Top comments (2)

Collapse
 
satyajitbarik profile image
Satyajit Barik • Edited

The whole working code here in below:

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

for i in string:
    if i.isupper():
        new_string.append(i.lower())
    else:
        new_string.append(i.upper())
print(''.join(new_string))

Enter fullscreen mode Exit fullscreen mode
Collapse
 
satyajitbarik profile image
Satyajit Barik • Edited

Hi, Bro this is not working. Unless you use new_string.append(i.lower()) in if condition and vice verse of else condition i.upper() of the code.