Search code examples
pythonpython-3.xstringconcatenation

Concatenating the common characters between two strings


So I am required to concatenate the similar characters from two strings. For example, String1 = 'harry' and String2 = 'hermione'. The output should be hrrhr. However, if there are no common characters I have to print Nothing in common. For example, string1 = 'dean' and string2 = 'tom'. In this case, the output has to be Nothing in common.

I think I've figured out the concatenating part. But I'm stuck in printing 'Nothing in common' when the strings share no common characters. Here goes my half-done code:

str1 = input('enter string1:')
str2 = input('enter string2:')

empty_str1 = ''
empty_str2 = ''

for i in str1:
    if i in str2:
        empty_str1 += i
for j in str2:
    if j in str1:
        empty_str2 += j
print(empty_str1 + empty_str2)

I get hrrhr as output when I enter 'harry' and 'hermione'. But I really can't figure out how to print 'Nothing in common' when I enter strings like 'dean' and 'tom'. Kindly help


Solution

  • Just check if the length of string empty_str1 + empty_str2 is 0

    x = empty_str1 + empty_str2
    if empty_str1 or empty_str2: 
         print(x) 
    else: 
         print("nothing in common")