Skip to content
geeksforgeeks
  • Courses
    • DSA to Development
    • Get IBM Certification
    • Newly Launched!
      • Master Django Framework
      • Become AWS Certified
    • For Working Professionals
      • Interview 101: DSA & System Design
      • Data Science Training Program
      • JAVA Backend Development (Live)
      • DevOps Engineering (LIVE)
      • Data Structures & Algorithms in Python
    • For Students
      • Placement Preparation Course
      • Data Science (Live)
      • Data Structure & Algorithm-Self Paced (C++/JAVA)
      • Master Competitive Programming (Live)
      • Full Stack Development with React & Node JS (Live)
    • Full Stack Development
    • Data Science Program
    • All Courses
  • Tutorials
    • Data Structures & Algorithms
    • ML & Data Science
    • Interview Corner
    • Programming Languages
    • Web Development
    • CS Subjects
    • DevOps And Linux
    • School Learning
  • Practice
    • Build your AI Agent
    • GfG 160
    • Problem of the Day
    • Practice Coding Problems
    • GfG SDE Sheet
  • Contests
    • Accenture Hackathon (Ending Soon!)
    • GfG Weekly [Rated Contest]
    • Job-A-Thon Hiring Challenge
    • All Contests and Events
  • Python Tutorial
  • Interview Questions
  • Python Quiz
  • Python Glossary
  • Python Projects
  • Practice Python
  • Data Science With Python
  • Python Web Dev
  • DSA with Python
  • Python OOPs
Open In App
Next Article:
Convert Hex To String Without 0X in Python
Next article icon

Concatenated string with uncommon characters in Python

Last Updated : 14 Jan, 2025
Comments
Improve
Suggest changes
Like Article
Like
Report

The goal is to combine two strings and identify the characters that appear in one string but not the other. These uncommon characters are then joined together in a specific order. In this article, we’ll explore various methods to solve this problem using Python.

Using set symmetric difference 

We can use the symmetric difference operation of the set to pull out all the uncommon characters from both the string and make a string.

Python
s1 = 'aacdb'   s2 = 'gafd'  # Find and join uncommon characters print(''.join(set(s1) ^ set(s2)))   

Output
fbgc 

Explanation:

  • set(s1) and set(2): This converts the string s1 and s2 into a set of unique characters. This removes any duplicates.
  • ^ (Symmetric Difference): This operator performs a symmetric difference between two sets. It returns all elements that are in either set(s1) or set(s2), but not in both.
  • ”.join(): ThisJoins the resulting set of characters back into a string without spaces.

Let’s understand different methods to concatenated string with uncommon characters .

Using collections.Counter

collections.Counter count the occurrences of each character in the combined strings, then filters out characters that appear more than once.

Python
from collections import Counter s1 = 'aacdb' s2 = 'gafd' f = Counter(s1 + s2)  # Filter and collect characters that appear only once res = [ch for ch in s1 + s2 if f[ch] == 1] print(''.join(res)) 

Output
cbgf 

Explanation:

  • Counter(str1 + str2): This counts all characters in the combined string str1 + str2.
  • List comprehension: This Filters out characters that appear more than once.
  • ”.join(result): This combines the filtered characters into a string.

Using Dictionary

This method uses a dictionary to manually count the frequency of characters in the combined strings, then filters out those that appear only once.

Python
s1 = 'aacdb' s2 = 'gafd'  # Initialize an empty dictionary f = {} for ch in s1 + s2:     f[ch] = f.get(ch, 0) + 1  # Filter characters that appear only once res = [ch for ch in s1 + s2 if f[ch] == 1] print(''.join(res)) 

Output
cbgf 

Explanation:

  • Frequency dictionary: It is used to count the occurrences of each character in the combined strings s1 + s2.
  • f[ch] == 1): This filters out characters that appear only once.
  • ”.join(res): This joins the filtered characters into a final string.

Using two pass filtering

This method identifies common characters between two strings and then filters them out in separate passes. It is simple but less efficient due to the extra overhead of processing the strings twice.

Python
s1 = 'aacdb' s2 = 'gafd' c = set(s1) & set(s2)  # Filter out common characters in two passes res = ''.join([ch for ch in s1 if ch not in c] + [ch for ch in s2 if ch not in c]) print(res) 

Output
cbgf 

Explanation:

  • set(s1) & set(s2): This finds the intersection of s1 and s2, i.e., the common characters.
  • Two-pass filtering: This filters the characters in both strings by checking if they are not in the common set.


Next Article
Convert Hex To String Without 0X in Python

S

Shashank Mishra
Improve
Article Tags :
  • DSA
  • Python
  • Strings
  • Python list-programs
  • Python set-programs
  • Python string-programs
  • python-list
  • python-set
  • python-string
Practice Tags :
  • python
  • python-list
  • python-set
  • Strings

Similar Reads

  • Find all duplicate characters in string in Python
    In this article, we will explore various methods to find all duplicate characters in string. The simplest approach is by using a loop with dictionary. Using Loop with DictionaryWe can use a for loop to find duplicate characters efficiently. First we count the occurrences of each character by iterati
    3 min read
  • Convert Hex To String Without 0X in Python
    Hexadecimal representation is a common format for expressing binary data in a human-readable form. In Python, converting hexadecimal values to strings is a frequent task, and developers often seek efficient and clean approaches. In this article, we'll explore three different methods to convert hex t
    2 min read
  • Python - Check if String Contain Only Defined Characters using Regex
    In this article, we are going to see how to check whether the given string contains only a certain set of characters in Python. These defined characters will be represented using sets. Examples: Input: ‘657’ let us say regular expression contains the following characters- (‘78653’) Output: Valid Exp
    2 min read
  • Count the number of Unique Characters in a String in Python
    We are given a string, and our task is to find the number of unique characters in it. For example, if the string is "hello world", the unique characters are {h, e, l, o, w, r, d}, so the output should be 8. Using setSet in Python is an unordered collection of unique elements automatically removing d
    2 min read
  • How to Convert Bytes to String in Python ?
    We are given data in bytes format and our task is to convert it into a readable string. This is common when dealing with files, network responses, or binary data. For example, if the input is b'hello', the output will be 'hello'. This article covers different ways to convert bytes into strings in Py
    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
  • Python String Concatenation
    String concatenation in Python allows us to combine two or more strings into one. In this article, we will explore various methods for achieving this. The most simple way to concatenate strings in Python is by using the + operator. Using + OperatorUsing + operator allows us to concatenation or join
    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 stri
    2 min read
  • Convert a String to Utf-8 in Python
    Unicode Transformation Format 8 (UTF-8) is a widely used character encoding that represents each character in a string using variable-length byte sequences. In Python, converting a string to UTF-8 is a common task, and there are several simple methods to achieve this. In this article, we will explor
    3 min read
  • Ways to Print Escape Characters in Python
    In Python, escape characters like \n (newline) and \t (tab) are used for formatting, with \n moving text to a new line and \t adding a tab space. By default, Python interprets these sequences, so I\nLove\tPython will display "Love" on a new line and a tab before "Python." However, if you want to dis
    2 min read
geeksforgeeks-footer-logo
Corporate & Communications Address:
A-143, 7th Floor, Sovereign Corporate Tower, Sector- 136, Noida, Uttar Pradesh (201305)
Registered Address:
K 061, Tower K, Gulshan Vivante Apartment, Sector 137, Noida, Gautam Buddh Nagar, Uttar Pradesh, 201305
GFG App on Play Store GFG App on App Store
Advertise with us
  • Company
  • About Us
  • Legal
  • Privacy Policy
  • In Media
  • Contact Us
  • Advertise with us
  • GFG Corporate Solution
  • Placement Training Program
  • Languages
  • Python
  • Java
  • C++
  • PHP
  • GoLang
  • SQL
  • R Language
  • Android Tutorial
  • Tutorials Archive
  • DSA
  • Data Structures
  • Algorithms
  • DSA for Beginners
  • Basic DSA Problems
  • DSA Roadmap
  • Top 100 DSA Interview Problems
  • DSA Roadmap by Sandeep Jain
  • All Cheat Sheets
  • Data Science & ML
  • Data Science With Python
  • Data Science For Beginner
  • Machine Learning
  • ML Maths
  • Data Visualisation
  • Pandas
  • NumPy
  • NLP
  • Deep Learning
  • Web Technologies
  • HTML
  • CSS
  • JavaScript
  • TypeScript
  • ReactJS
  • NextJS
  • Bootstrap
  • Web Design
  • Python Tutorial
  • Python Programming Examples
  • Python Projects
  • Python Tkinter
  • Python Web Scraping
  • OpenCV Tutorial
  • Python Interview Question
  • Django
  • Computer Science
  • Operating Systems
  • Computer Network
  • Database Management System
  • Software Engineering
  • Digital Logic Design
  • Engineering Maths
  • Software Development
  • Software Testing
  • DevOps
  • Git
  • Linux
  • AWS
  • Docker
  • Kubernetes
  • Azure
  • GCP
  • DevOps Roadmap
  • System Design
  • High Level Design
  • Low Level Design
  • UML Diagrams
  • Interview Guide
  • Design Patterns
  • OOAD
  • System Design Bootcamp
  • Interview Questions
  • Inteview Preparation
  • Competitive Programming
  • Top DS or Algo for CP
  • Company-Wise Recruitment Process
  • Company-Wise Preparation
  • Aptitude Preparation
  • Puzzles
  • School Subjects
  • Mathematics
  • Physics
  • Chemistry
  • Biology
  • Social Science
  • English Grammar
  • Commerce
  • World GK
  • GeeksforGeeks Videos
  • DSA
  • Python
  • Java
  • C++
  • Web Development
  • Data Science
  • CS Subjects
@GeeksforGeeks, Sanchhaya Education Private Limited, All rights reserved
We use cookies to ensure you have the best browsing experience on our website. By using our site, you acknowledge that you have read and understood our Cookie Policy & Privacy Policy
Lightbox
Improvement
Suggest Changes
Help us improve. Share your suggestions to enhance the article. Contribute your expertise and make a difference in the GeeksforGeeks portal.
geeksforgeeks-suggest-icon
Create Improvement
Enhance the article with your expertise. Contribute to the GeeksforGeeks community and help create better learning resources for all.
geeksforgeeks-improvement-icon
Suggest Changes
min 4 words, max Words Limit:1000

Thank You!

Your suggestions are valuable to us.

What kind of Experience do you want to share?

Interview Experiences
Admission Experiences
Career Journeys
Work Experiences
Campus Experiences
Competitive Exam Experiences