HackerRank Solution: Python sWAP cASE [3 Methods]


Bashir Alam

Hacker Rank Python

Question: Python sWAP cASE [Strings]

You are given a string and your task is to swap cases. In other words, convert all lowercase letters to uppercase letters and vice versa.

For example:

Www.HackerRank.com → wWW.hACKERrANK.COM
Pythonist 2 → pYTHONIST 2

Input format:

A single line containing a string S.

Constraints:

0 < len(S) <= 1000

Output format:

Print the modified string S.

Sample input 0:

HackerRank.com presents "Pythonist 2".

Sample output 0:

hACKERrANK.COM PRESENTS "pYTHONIST 2".

 

Possible solutions

Now let us jump into possible solutions for the given problem. The following Python code is already given in the editor of the Hacker Rank:

def swap_case(s):
    return

if __name__ == '__main__':
    s = input()
    result = swap_case(s)
    print(result)

Now let us jump into the solutions:

 

Solution-1: Using if-else statements

Let us use the if-else statements to solve the problem:

def swap_case(s):
    SwAp = ''
    for char in s:
        if char.upper() != char:
            SwAp += char.upper()
        elif char.lower() != char:
            SwAp += char.lower()
        else:
            SwAp += char
    
    
    return SwAp

if __name__ == '__main__':
    s = input()
    result = swap_case(s)
    print(result)

This code defines a function called "swap_case" which takes a string as input and returns a new string where all the uppercase letters are converted to lowercase and all the lowercase letters are converted to uppercase. The function creates an empty string called "SwAp" and then iterates through each character in the input string. For each character, it checks if the character is uppercase or lowercase and if it is uppercase it converts it to lowercase and adds it to the "SwAp" string, if it is lowercase it converts it to uppercase and adds it to the "SwAp" string, and if it is neither uppercase or lowercase it simply adds the character to the "SwAp" string. Finally, the function returns the modified "SwAp" string. If the script is run as the main program, it takes a string input from the user and prints the result of the swap_case function applied to that input string.

 

Solution-2: swapcase() method

Now, let us use the swapcase() method to solve the given problem:

def swap_case(s):
    return s.swapcase()


if __name__ == '__main__':
    s = input()
    result = swap_case(s)
    print(result)

This code defines a function called "swap_case" which takes a string as input and uses the built-in string method "swapcase()" to return a new string where all the uppercase letters are converted to lowercase and all the lowercase letters are converted to uppercase. If the script is run as the main program, it takes a string input from the user and prints the result of the swap_case function applied to that input string. The function swapcase() is a built-in python method and it is more efficient than the previous implementation because it performs the same task in a single line of code which is much more readable, maintainable and efficient.

 

Solution-3: Alternative method

Now, we will modify the first solution and solve the problem in an alternative method:

def swap_case(s):
    ans = list(s)
    for i in range(len(ans)):
        if ans[i].islower(): ans[i] = ans[i].upper()
        elif ans[i].isupper(): ans[i] = ans[i].lower()  
    return "".join(ans) 
if __name__ == '__main__':
    s = input()
    result = swap_case(s)
    print(result)

Similar to previous solutions, this solution also defines a function called "swap_case" that takes a string as input, converts it into a list of characters, iterates through each character, and checks if the character is uppercase or lowercase using the built-in string methods islower() and isupper(). If the character is lowercase, it converts it to uppercase using the built-in string method upper() and if it is uppercase it converts it to lowercase using the built-in string method lower(). The final list of characters is then joined together to form a single string and returned as output. This implementation is different from the previous two in that it uses a for loop to iterate through the characters of the input string and uses built-in string methods to check the case of each character and convert them, which makes it more readable and efficient than the first implementation, and more efficient and readable than the second one.

 

Summary

In this short article, we discussed how we can solve the sWAP cASE problem from hacker rank. We covered three different solutions and explained each one.

 

Further reading

Question on hacker rank

 

Views: 250

Bashir Alam

He is a Computer Science graduate from the University of Central Asia, currently employed as a full-time Machine Learning Engineer at uExel. His expertise lies in OCR, text extraction, data preprocessing, and predictive models. You can reach out to him on his Linkedin or check his projects on GitHub page.

Can't find what you're searching for? Let us assist you.

Enter your query below, and we'll provide instant results tailored to your needs.

If my articles on GoLinuxCloud has helped you, kindly consider buying me a coffee as a token of appreciation.

Buy GoLinuxCloud a Coffee

For any other feedbacks or questions you can send mail to admin@golinuxcloud.com

Thank You for your support!!

Leave a Comment

GoLinuxCloud Logo


We try to offer easy-to-follow guides and tips on various topics such as Linux, Cloud Computing, Programming Languages, Ethical Hacking and much more.

Programming Languages

JavaScript

Python

Golang

Node.js

Java

Laravel