
Data Structure
Networking
RDBMS
Operating System
Java
MS Excel
iOS
HTML
CSS
Android
Python
C Programming
C++
C#
MongoDB
MySQL
Javascript
PHP
- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who
Generate two output strings depending upon occurrence of character in input string in Python
In Python, a string is one of the data structures that is a sequence of characters enclosed within single quotes '' or double quotes "". It is immutable, i.e., once a string is created, it cannot be changed.
When we want to generate two output strings based on character occurrence in Python, we have to follow the steps below -
- First, we need to initialize a dictionary or use the collections.Counter class to count the frequency of each character in the input string.
- Next, we have to go through the input string and, based on the count of each character, generate two new strings -
- The first string will contain characters that appear only once.
- The second string will contain characters that appear more than once.
- Finally, we have to join all the characters to form the required output strings.
Using collections.Counter class
The collections.Counter is a class in Python's collections module is used to count the frequency of elements in an iterable. It returns a dictionary-like object where elements are stored as dictionary keys and their counts as dictionary values.
Example
In this example, we will count the frequency of characters and based on their occurrence, we will generate two strings as one with characters occurring only once and another with characters occurring more than once, with the help of collections.counter class -
from collections import Counter def Inputstrings(load): Dict = Counter(load) occurrence = [key for (key, value) in Dict.items() if value == 1] occurrence_1 = [key for (key, value) in Dict.items() if value > 1] occurrence.sort() occurrence_1.sort() print('characters occurring once:') print(''.join(occurrence)) print('characters occurring more than once:') print(''.join(occurrence_1)) if __name__ == "__main__": load = "Tutorialspoint has best tutorials" Inputstrings(load)
Following is the output of the above example -
PS D:\Tutorialspoint\Articles> python sample.py characters occurring once: Tbehnp characters occurring more than once: ailorstu