The Wayback Machine - https://web.archive.org/web/20240618033856/https://www.geeksforgeeks.org/python-toggle-characters-in-words-having-same-case/
Open In App

Python | Toggle characters in words having same case

Last Updated : 09 Mar, 2023
Improve
Improve
Like Article
Like
Save
Share
Report

Given a string, toggle the characters of those words who have all their characters in the same case. 

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: Consider each word in the string separately. Set two flags, one to check if all the cases of the characters are the same and another to check if the characters are upper case or 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: 

Python3




# Python program to toggle character in
# a string only with same case
 
# Function to toggle case
def toggle(s):
     
    word_list = s.split()
     
    # traverse through each word of the string
    for word in word_list:
         
        # initially assume all the characters in word
        # are in the same case and set the flag to 1
        flag = 1
         
        # check the case of the first
        # character in the word
        if word[0].islower():
             
            # if the case is lower set the r value to 1
            r = 1
             
            # traverse through the remaining
            # characters in the word
            for j in word:
                 
                # if any of the characters are in upper case
                if j.isupper():
                     
                    # then set the flag to 0
                    flag = 0
                    break
                 
        else:
            # if the case is upper
            # set the r value to 1
            r = 0
             
            # traverse through the remaining
            # characters in the word
            for j in word:
                 
                # if any of the characters are in lower case
                if j.islower():
                     
                    # then set the flag to 0
                    flag = 0
                    break
         
        # if the flag is 0 then print the word as it is   
        if flag == 0: print(word, end =" ")
     
        else:
            # if the word is in lower case
            # then print the word in upper case
            if r == 1: print(word.upper(), end =" ")
             
            # if the word is in upper case
            # then print the word in lower case
            else: print(word.lower(), end =" ")
             
# driver code
s = 'Geeks for Geeks'
toggle(s)


Output

Geeks FOR Geeks 

Complexity Analysis:

  • Time Complexity: O(n)
  • Auxiliary Space: O(n)

Using Library functions : We can also use direct library functions to check if individual words are lower or upper. 

Python3




# Python program to toggle character in
# a string only with same case
 
# Function to toggle case
def toggle(s):
     
    word_list = s.split()
     
    # traverse through each word of the string
    for word in word_list:
         
        if word.islower() :
            print(word.upper(), end =" ")
        elif word.isupper() :
            print(word.lower(), end =" ")
        else :
            print(word, end =" ")
             
# driver code
s = 'Geeks for Geeks'
toggle(s)


Output

Geeks FOR Geeks 

Complexity Analysis:

  • Time Complexity: O(n)
  • Auxiliary Space: O(n)

Using all() and list comprehension:

Here is a new approach Using all() and list comprehension.

Python3




def toggle_words(s):
    def toggle_word(word):
        if all(c.isupper() for c in word):
            return word.lower()
        elif all(c.islower() for c in word):
            return word.upper()
        else:
            return word
    return ' '.join(toggle_word(word) for word in s.split())
 
# Test the function
s = 'Geeks for Geeks'
print(toggle_words(s))  # Output: 'Geeks FOR Geeks'
 
s = 'HELLO world'
print(toggle_words(s))  # Output: 'hello WORLD'
 
#This code is contributed by Edula Vinay Kumar Reddy


Output

Geeks FOR Geeks
hello WORLD

This approach defines a generator function toggle_word which yields the toggled case of a single word. The generator function is used in a list comprehension to toggle the case of each word in the input string, and the resulting list is joined with spaces to form the final output string.

The time complexity of this approach is O(n), where n is the length of the input string. The space complexity is also O(n), as the input string is split into a list of words, and the output string is constructed by joining the toggled words with spaces. 



Similar Reads

Toggle case of a string using Bitwise Operators
Given a string, write a function that returns toggle case of a string using the bitwise operators in place.In ASCII codes, character ‘A’ is integer 65 = (0100 0001)2, while character ‘a’ is integer 97 = (0110 0001)2. Similarly, character 'D' is integer 68 = (0100 0100)2, while character 'd' is integer 100 = (0110 0100)2. As we can see, only sixth l
4 min read
Minimum number of operations to move all uppercase characters before all lower case characters
Given a string str, containing upper case and lower case characters. In a single operations, any lowercase character can be converted to an uppercase character and vice versa. The task is to print the minimum number of such operations required so that the resultant string consists of zero or more upper case characters followed by zero or more lower
8 min read
Python regex to find sequences of one upper case letter followed by lower case letters
Write a Python Program to find sequences of one upper case letter followed by lower case letters. If found, print 'Yes', otherwise 'No'. Examples: Input : GeeksOutput : YesInput : geeksforgeeksOutput : NoPython regex to find sequences of one upper case letter followed by lower case lettersUsing re.search() To check if the sequence of one upper case
2 min read
Python program to convert camel case string to snake case
Given a string in camel case, write a Python program to convert the given string from camel case to snake case.Examples: Input : GeeksForGeeks Output : geeks_for_geeks Input : ThisIsInCamelCase Output : this_is_in_camel_case Let's see the different ways we can do this task. Method #1 : Naive ApproachThis is a naive implementation to convert camel c
4 min read
Python - Convert Snake case to Pascal case
Sometimes, while working with Python Strings, we have problem in which we need to perform a case conversion of String. This a very common problem. This can have application in many domains such as web development. Lets discuss certain ways in which this task can be performed. Input : geeks_for_geeks Output : GeeksforGeeks Input : left_index Output
7 min read
Python - Convert Snake Case String to Camel Case
Given a snake case string, convert to camel case. Input : test_str = 'geeksforgeeks_is_best_for_geeks' Output : geeksforgeeksIsBestForGeeks Explanation : String converted to Camel Case. Input : test_str = 'geeksforgeeks_best_for_geeks' Output : geeksforgeeksBestForGeeks Explanation : String converted to Camel Case. Method #1: Using split() + join()
4 min read
Group words with same set of characters
Given a list of words with lower cases. Implement a function to find all Words that have the same unique character set. Example: Input: words[] = { "may", "student", "students", "dog", "studentssess", "god", "cat", "act", "tab", "bat", "flow", "wolf", "lambs", "amy", "yam", "balms", "looped", "poodle"}; Output : looped, poodle, lambs, balms, flow,
8 min read
Capitalize 1st character of all words having at least K characters
Given string str representing a sentence, and an integer K, the task is to capitalize all the words in the given sentence having at least K characters. Example: Input: str = "geeks for geeks", K = 4Output: Geeks for GeeksExplanation: The word "for" does not contain 4 characters, hence its 1st character is not capitalize. Input: str = "geeksforgeeks
5 min read
Convert camel case string to snake case in Java
Given a string in camel case, the task is to write a Java program to convert the given string from camel case to snake case and print the modified string. Examples: Input: GeeksForGeeks Output: geeks_for_geeks Input: CamelCaseToSnakeCase Output: camel_case_to_snake_case Method 1: Naive Approach First we initialize a variable 'result' with an empty
3 min read
Convert Snake Case string to Camel Case in Java
Given a string in Snake Case, the task is to write a Java program to convert the given string from snake case to camel case and print the modified string. Examples: Input: str = "geeks_for_geeks" Output: GeeksForGeeks Input: str = "snake_case_to_camel_case" Output: SnakeCaseToCamelCase Method 1: Using TraversalThe idea is to first capitalize the fi
3 min read
Practice Tags :