简体   繁体   English

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

[英]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'.例如,String1 = 'harry' 和 String2 = 'hermione'。 The output should be hrrhr . output 应该是hrrhr However, if there are no common characters I have to print Nothing in common.但是,如果没有共同的字符,我必须打印Nothing in common。 For example, string1 = 'dean' and string2 = 'tom'.例如,string1 = 'dean' 和 string2 = 'tom'。 In this case, the output has to be Nothing in common.在这种情况下,output 必须没有共同点。

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'.当我输入“harry”和“hermione”时,我得到的hrrhr为 output。 But I really can't figure out how to print 'Nothing in common' when I enter strings like 'dean' and 'tom'.但是当我输入像'dean'和'tom'这样的字符串时,我真的不知道如何打印'Nothing in common'。 Kindly help请帮助

Just check if the length of string empty_str1 + empty_str2 is 0只需检查字符串empty_str1 + empty_str2的长度是否为 0

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM