连接两个字符串之间的公共字符

时间:2021-02-23 05:52:08

标签: python python-3.x string concatenation

所以我需要连接两个字符串中的相似字符。例如,String1 = 'harry' 和 String2 = 'hermione'。输出应该是hrhrr。但是,如果没有通用字符,我必须打印Nothing in common。 例如,string1 = 'dean' 和 string2 = 'tom'。在这种情况下,输出必须没有共同点。

我想我已经弄清楚了连接部分。但是当字符串不共享公共字符时,我一直在打印“Nothing in common”。这是我的半成品代码:

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)

当我输入 'harry' 和 'hermione' 时,我得到 hrrhr 作为输出。但是当我输入像“dean”和“tom”这样的字符串时,我真的不知道如何打印“Nothing in common”。请帮忙

1 个答案:

答案 0 :(得分:2)

检查字符串 empty_str1 + empty_str2 的长度是否为 0

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