In this tutorial, we will learn writing the python program to print all characters of the string which are not repeating. We can say the character are available only one time in string.
Problem Statement
Take any string as an input from the user and check if any character in the string is repeating or not. if it is not repeating then print that character as output.
For example:
Case1: If the user inputs the string ‘pythonprogramming’
Then the output should be ‘ythai’, where there is no character that is repeating.
Case2: If the user inputs the string ‘quescoll’
Then the output should be ‘quesco’, where there is no character that is repeating.
Our logic to find all non repeating characters in the string
- Our program will take a string as an input from the user.
- Iterate the character of the input string to check if the character is repeating or not, to achieve this we use the concept of ‘nested loop’.
- The output is in the form of a string, where all the non-repeating characters are concatenated together using concatenation methods.
Python code to find all nonrepeating characters in the String
Program 1: Using a Dictionary to Count Occurrences
This method uses a dictionary to count how many times each character appears in the string, and then collects those characters that appear exactly once.
string = input('Please enter a string: ')
freq_dict = {}
for char in string:
if char in freq_dict:
freq_dict[char] += 1
else:
freq_dict[char] = 1
non_repeating_chars = ""
for char in string:
if freq_dict[char] == 1:
non_repeating_chars += char
print("Non-repeating characters:", non_repeating_chars)
Output
Please enter a string: hello quescol
Non-repeating characters: h qusc
Explanation
For the input string ‘hello quescol’, as the characters ‘e’, ‘l’,’o’ are repeating but ‘h’, ‘q’, ‘s’, and ‘c’ are not repeating so the generated output should be ‘h qusc’.
Program 2: Using Collections.Counter
Python’s collections
module provides a Counter
class which is a more efficient and cleaner way to count occurrences. After counting, it similarly collects characters that appear only once.
from collections import Counter
string = input('Please enter a string: ')
counts = Counter(string)
non_repeating = [char for char, count in counts.items() if count == 1]
print("non repeating characters = ", non_repeating)
Output
Please enter a string: hello
non repeating characters = ['h', 'e', 'o']
Explanation
The Counter
object automatically counts the occurrences of each character. The list comprehension then filters out those characters that appear exactly once.