sWAP cASE HackerRank Solution In Python

Problem

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.COMPythonist 2 → pYTHONIST 2  

Function Description

Complete the swap_case function in the editor below.

swap_case has the following parameters:

  • string s: the string to modify
Returns
  • string: the modified string

Input Format

A single line containing a string s.

Constraints

0 ≤ len(s) ≤ 1000

Sample Input 0

HackerRank.com presents "Pythonist 2".

Sample Output 0

hACKERrANK.COM PRESENTS "pYTHONIST 2".

Solution to HackerRank sWAP cASE In Python3

In this problem, we are to convert all uppercase letters to lowercase and vice versa.

case swap hackerrank solution
def swap_case(s):    inverse_list = list()    for x in s:        if x.isupper():            x = x.lower()        else:            x = x.upper()        inverse_list.insert(len(s) -1, x)    return ''.join(inverse_list)if __name__ == '__main__':    s = input()    result = swap_case(s)    print(result)

Alternative Method

The alternative method for solving this problem is by using the swapcase() built-in function.

if __name__ == '__main__':    s = input()    print(s.swapcase())

Comments