查找两个字符串之间的公共字符

JMa*_*tth 3 python for-loop python-3.x

我正在尝试使用for循环打印来自两个不同用户输入的常见字母。(我需要使用 for 循环来完成。)我遇到了两个问题: 1. 我的语句“If char not in output...”没有提取唯一值。2. 输出给了我一个单独字母的列表,而不是一个字符串。我尝试拆分输出但拆分遇到了类型错误。

wrd = 'one'
sec_wrd = 'toe'

def unique_letters(x): 
    output =[]
    for char in x: 
        if char not in output and char != " ": 
            output.append(char)
    return output

final_output = (unique_letters(wrd) + unique_letters(sec_wrd))

print(sorted(final_output))
Run Code Online (Sandbox Code Playgroud)

Moi*_*dri 11

您正在尝试执行Set Intersection。Python 有set.intersection同样的方法。您可以将它用于您的用例:

>>> word_1 = 'one'
>>> word_2 = 'toe'

#    v join the intersection of `set`s to get back the string
#    v                             v  No need to type-cast it to `set`.
#    v                             v  Python takes care of it
>>> ''.join(set(word_1).intersection(word_2))
'oe'
Run Code Online (Sandbox Code Playgroud)

set将返回字符串中的唯一字符。set.intersection方法将返回两个集合中共有的字符。


如果for您必须使用循环,那么您可以使用列表推导式:

>>> unique_1 = [w for w in set(word_1) if w in word_2]
# OR
# >>> unique_2 = [w for w in set(word_2) if w in word_1]

>>> ''.join(unique_1)  # Or, ''.join(unique_2)
'oe'
Run Code Online (Sandbox Code Playgroud)

上述结果也可以通过显式for循环实现:

my_str = ''
for w in set(word_1):
    if w in word_2:
        my_str += w

# where `my_str` will hold `'oe'`
Run Code Online (Sandbox Code Playgroud)