Table of Contents
ToggleQuestion
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
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
def swap_case(s):
num = ""
for let in s:
if let.isupper() == True:
num+=(let.lower())
else:
num+=(let.upper())
return num
if __name__ == '__main__':
s = input()
result = swap_case(s)
print(result)
If the character is uppercase, it converts it to lowercase using the lower()
method and appends it to the num
string. If the character is not uppercase (i.e., it is lowercase or not a letter), it converts it to uppercase using the upper()
method and appends it to the num
string.
Finally, the num
string, which contains the swapped case version of the input string, is returned.
In the main part of the code, it first reads an input string s
using the input()
function. Then it calls the swap_case
function with the input string s
as an argument and stores the result in the variable result
. Finally, it prints the result
.
Overall, the code takes an input string and converts all lowercase letters to uppercase and vice versa, resulting in a string with the swapped case.
If you find anything wrong in this Solution, feel free to reach us in the comment section.
Nice
Thank you for your kind words…