Swapcase in python

Swap case in python

The program gets a string as input from the user and converts all the lower case letters to upper case and all upper case letters to lower case.

For example,

Sample input :

Hello Everyone

Sample output :

hELLO eVERYONE

Explanation :

In the above sample, for the string “Hello Everyone”, the characters “H” and “E” is in upper case and the rest characters are in lowercase. So the output should be “hELLO eVERYONE” where the characters “h” and “e” are alone in lower case and the rest characters are in upper case.

Method 1 (without using swap case function)

Procedure :

1. Start.

2. Get the string as input from the user.

3. Initialize the swapped string.

4. loop ( 0 to len(string) )

    => check if the character is in lower case.

        => subtract 32 from the ASCII value of the character.

    => check if the character is in upper case.

        => add 32 to the ASCII value of the character.

    => convert the ascii value to character and append it to the string.

5. Print the swapped string.

6. End.

Code :

#get the string as input from the user

s = str(input("Enter the string : "))

#initialize the swapped string

swapped_string = ""

for i in range(len(s)) :

#check if the character is in lower case (ascii value from 97)

if(ord(s[i]) >= 97):

#calculate the ascii value of the corresponding upper case letter

ascii = ord(s[i]) - 32

#check if the character is in upper case (ascii value from 65 to 97)

if(ord(s[i]) < 97):

#calculate the ascii value of the corresponding lower case letter

ascii = ord(s[i]) + 32

#convert the scii into character and append it to the swapped string

swapped_string += chr(ascii)

#print the swapped string

print(swapped_string)

Sample input 1 :

TechieeBytes

Sample output 1 :

tECHIEEbYTES

Output screenshot :

Swapcase in python
swapcase - output




Method 2 (using swapcase() function)

Procedure :

1. Start.

2. Get the string as input from the user.

3. Swap the given string using swap case function.

4. Print the swapped string.

5. End.

Code :

#get the string as input from the user

s = str(input("Enter the string : "))

#swap the given string

swapped_string = s.swapcase()

#print the swapped string

print(swapped_string)

Sample input 2 :

TECHIEEBYTES

Sample output 2 :

techieebytes

Output screenshot :

Swapcase in python
swapcase - output


 

 

 

Comments

Popular posts from this blog

Finding the percentage in python - HackerRank solution

HackerRank challenges with solutions (Rearrangement, Formula, Word sorting, Numbers, Sentence)

What's your name, Tuple - HackerRank solution in python