Computer >> Computer tutorials >  >> Programming >> Python

Concatenated string with uncommon characters in Python program


We have given two strings and our goal to get a new string that has unique characters from both the strings. For suppose, if we have two strings hafeez and kareem then, the new string which will be generated from the two strings is hfzkrm. We aim to get different characters from two strings. Think about the logic once before going to follow my steps.

Follow the below steps if you are not able to think about the logic for the program.

Algorithm

1. Initialize the string.
2. Initialize an empty string.
3. Loop over the first string.
   3.1. Check whether the current char is in the second string or not.
      3.1.1. If it's not in the second string, then add it to the empty string.
4. Loop over the second string.
   4.1. Check whether the current char is in the first string or not.
      4.1.1. If it's not in the first string, then add it to the empty string.
5. Print the resultant string.

Let's examine the code of the program.

Example

## initializing the strings
string_1 = "hafeez"
string_2 = "kareem"
## initializing an empty string
new_string = ""
## iterating through the first string
for char in string_1:
   ## checking is the char is in string_2 or not
   if char not in string_2:
      ## adding the char to new_string
      new_string += char
## iterating through the second string
for char in string_2:
   ## checking is the char is in string_1 or not
   if char not in string_1:
      ## adding the char to new_string
      new_string += char
## printing the new_string
print(f"New String: {new_string}")

Output

If you run the above program, you will get the following output.

New String: hfzkrm

Conclusion

If you have any doubts regarding the tutorial, mention them in the comment section.