Python | Switch characters in words with the same case

Python Methods and Functions

Examples :

Input: Geeks for Geeks
Output: Geeks FOR Geeks
Explanation: The string contains three words “Geeks”, “for”, “Geeks” out of which the word “for” contains all its characters as lower cases, therefore, toggle the case of the word. Print the remaining characters as it is.

Input: HELLO world
Output: hello WORLD

Simple approach:
Let`s look at each word in the line separately. Select two checkboxes, one to check if all the characters are the same and the other to check if all the characters are lower case.

 if all the characters are in the same case if all the characters are lower case then convert into upper case else convert into lower case else print the same word 

Below is the implementation:

# Python program to toggle symbols in
# line with only the same case

 
# Case toggle function

def toggle (s) :

 

word_list = s.split ()

 

# go through each word in the line

for word in word_list:

 

# initially accept all characters in a word

# in the same case and set the flag to 1

flag = 1

 

# check the case of the first

# character in word  

if word [ 0 ]. islower ():

 

# if lower case, set r to 1

r = 1

 

# go through remaining

# characters per word

for j in word:

 

# if any of the uppercase characters

if j.isupper ():

 

  # then set the flag to 0

  flag = 0

  break

 

  else :

  # if uppercase

# set r value in 1

r = 0

 

# go through the remaining

# characters in a word

  for j in word:

  

# if any of the characters is in lowercase

if j.islower ():

 

# then set the flag to 0

flag = 0

break

 

# if the flag is 0, print word as is

if flag = = 0 : print (word, end = "" )

 

else :

# if the word is in lower case

# then n type the word in uppercase

if r = = 1 : print (word.upper (), end = "" )

 

# if the word is in uppercase

  # then type in lowercase

  else : print (word.lower () , end = "" )

  
# driver code

s = `Geeks for Geeks`

toggle (s)

Exit:

 Geeks FOR Geeks  

Using library functions:
We can also use direct library functions to check if individual isupper-islower -lower-upper-python-applications /> words upper or lower.

# Python program to toggle characters in
# string with only the same case

 
# Case switching function

def < / code> toggle (s):

 

word_list = s.split ()

 

# go through each word of the line

for word in word_list:

  

if word.islower () :

print (word.upper (), end = "" )

  elif word.isupper ():

  print (word.lower (), end = "" )

  else :

print (word, end = "" )

 
# code driver

s = `Geeks for Geeks `

toggle (s)

Exit:

 Geeks FOR Geeks 




Get Solution for free from DataCamp guru