Generate Two Output Strings Depending upon Occurrence of Character in Input String - Python Last Updated : 30 Jan, 2025 Comments Improve Suggest changes Like Article Like Report The task of generating two output strings based on the occurrence of characters in an input string in Python involves classifying characters based on their frequency. We need to create one string that contains characters that appear only once in the input string and another string for characters that appear more than once. For example, given the string s = "geeksforgeeks", the first output string should contain characters that appear once, while the second output string will contain characters that appear more than once.Using collections.Counter Counter from the collections module efficiently count the frequency of characters in a string. It then separates the characters into two lists . One for characters occurring once and another for those occurring more than once. Finally, both lists are sorted alphabetically and joined into strings for output. Python from collections import Counter s = "hello" d = Counter(s) # create counter object # Separate characters into those with count 1 and greater than 1 a = [char for char, count in d.items() if count == 1] b = [char for char, count in d.items() if count > 1] print(''.join(sorted(a))) print(''.join(sorted(b))) Outputeho l Explanation:Two lists are created where a contains characters with count of 1 and b contains characters with count greater than 1.Both lists are sorted alphabetically using sorted() and then joined into strings with ''.join().Table of ContentUsing for loopUsing defaultdictUsing itertools.groupby()Using for loopThis method counts character frequencies in a string by going through it just once, storing the counts in a dictionary. After counting, it separates the characters into two lists. The lists are then sorted and combined into strings. This approach is efficient as it avoids repeatedly counting characters and ensures faster processing by using a single pass through the string. Python s = "hello" d = {} # Single pass over input string to count frequencies for char in s: d[char] = d.get(char, 0) + 1 # Separate characters into two lists a = [char for char, count in d.items() if count == 1] b = [char for char, count in d.items() if count > 1] print(''.join(sorted(a))) print(''.join(sorted(b))) Outputeho l Explanation:split characters into two lists, one for those occurring once and another for those occurring more than once.sort both lists alphabetically and join them into strings for display.Using defaultdictThis approach uses defaultdict to count the frequency of characters in the input string, where each character is initialized with a default count of 0. The characters are then divided into two groups. Both groups are sorted alphabetically and returned as strings.Example: Python from collections import defaultdict s = "hello" count = defaultdict(int) # Creates a defaultdict for char in s: count[char] += 1 a = [char for char, freq in count.items() if freq == 1] b = [char for char, freq in count.items() if freq > 1] print(''.join(sorted(a))) print(''.join(sorted(b))) Outputeho l Explanation:for char in s loops through each character in the input string s and increments its count in the count dictionary. If the character doesn't exist, it's initialized to 0 and incremented by 1.Two lists are created where a contains characters with count of 1 and b contains characters with count greater than 1 and Both lists are sorted alphabetically using sorted() and then joined into strings with ''.join().Using itertools.groupby()itertools.groupby from itertools groups consecutive occurrences of the same element. This method requires sorting the string first, making it less efficient compared to single-pass methods like Counter and defaultdict. Python from itertools import groupby s = "hello" sorted_s = sorted(s) # Sorts the input string `s` alphabetically a = [] # initialize empty list to store characters that appear once b = [] # initialize empty list to store characters that appear more than once for char, group in groupby(sorted_s): if len(list(group)) == 1: a.append(char) else: b.append(char) print(''.join(sorted(a))) print(''.join(sorted(b))) Outputeho l Explanation:for char, group in groupby(sorted_s) iterates over the sorted string grouping consecutive occurrences of each character.if len(list(group)) == 1 adds characters that appear once to a otherwise adds characters that appear more than once to b. Comment More infoAdvertise with us Next Article Generate Two Output Strings Depending upon Occurrence of Character in Input String - Python S Shashank Mishra Follow Improve Article Tags : Strings Python DSA python-string Practice Tags : pythonStrings Similar Reads Python - Replacing Nth occurrence of multiple characters in a String with the given character Replacing the Nth occurrence of multiple characters in a string with a given character involves identifying and counting specific character occurrences.Using a Loop and find()Using a loop and find() method allows us to search for the first occurrence of a substring within each list element. This app 2 min read Python - Replace all occurrences of a substring in a string Replacing all occurrences of a substring in a string means identifying every instance of a specific sequence of characters within a string and substituting it with another sequence of characters. Using replace()replace () method is the most straightforward and efficient way to replace all occurrence 2 min read Replacing Characters in a String Using Dictionary in Python In Python, we can replace characters in a string dynamically based on a dictionary. Each key in the dictionary represents the character to be replaced, and its value specifies the replacement. For example, given the string "hello world" and a dictionary {'h': 'H', 'o': 'O'}, the output would be "Hel 2 min read Capitalize Each String in a List of Strings in Python In Python, manipulating strings is a common task, and capitalizing each string in a list is a straightforward yet essential operation. This article explores some simple and commonly used methods to achieve this goal. Each method has its advantages and use cases, providing flexibility for different s 3 min read Convert a List of Characters into a String - Python Our task is to convert a list of characters into a single string. For example, if the input is ['H', 'e', 'l', 'l', 'o'], the output should be "Hello".Using join() We can convert a list of characters into a string using join() method, this method concatenates the list elements (which should be strin 2 min read Python - Check if substring present in string The task is to check if a specific substring is present within a larger string. Python offers several methods to perform this check, from simple string methods to more advanced techniques. In this article, we'll explore these different methods to efficiently perform this check.Using in operatorThis 2 min read Python counter and dictionary intersection example (Make a string using deletion and rearrangement) Given two strings, find if we can make first string from second by deleting some characters from second and rearranging remaining characters. Examples: Input : s1 = ABHISHEKsinGH : s2 = gfhfBHkooIHnfndSHEKsiAnG Output : Possible Input : s1 = Hello : s2 = dnaKfhelddf Output : Not Possible Input : s1 2 min read Possible Words using given characters in Python Given a dictionary and a character array, print all valid words that are possible using characters from the array. Note: Repetitions of characters is not allowed. Examples: Input : Dict = ["go","bat","me","eat","goal","boy", "run"] arr = ['e','o','b', 'a','m','g', 'l'] Output : go, me, goal. This pr 5 min read Combine similar characters in Python using Dictionary Get() Method Let us see how to combine similar characters in a list. Example : Input : ['g', 'e', 'e', 'k', 's', 'f', 'o', 'r', 'g', 'e', 'e', 'k', 's'] Output : ['gg', 'eeee', 'kk', 'ss', 'f', 'o', 'r'] We will be using the get() method of the dictionary class. dictionary.get() The get() method returns the valu 3 min read Python Set | Check whether a given string is Heterogram or not Given a string S of lowercase characters. The task is to check whether a given string is a Heterogram or not using Python. A heterogram is a word, phrase, or sentence in which no letter of the alphabet occurs more than once. Input1: S = "the big dwarf only jumps"Output1: YesExplanation: Each alphabe 3 min read Like