在python中使用set来查找来自两个字符串的公共字母

时间:2015-10-27 19:45:23

标签: python string python-3.x set

我正在尝试编写一个程序,该程序基本上需要两个字符串并找到两个字母的常用字母,并从中查找不常见的字母。它还必须在字符串中找到数字和特殊字符,并在打印命令中显示它们。

这是我的代码

from string import ascii_letters
import re
import itertools

def main():
    s1 = input("Please enter string 1: ")
    s2 = input("Please enter string 2: ")
    ch=""
    lowercase_letters = [i for i in s1 if i.islower() and i in s2]
    #print(lowercase_letters)
    uppercase_letters = [i for i in s1 if i.isupper() and i in s2]
    # print(uppercase_letters)
    new_str=''.join(uppercase_letters+lowercase_letters)
    print("The set consisting of the upper and lowercase letters that are contained in both strings is: ", new_str)

    # stringFunction(s1, s2)
    # k= str(longest_common_substring(s1,s2))
    # print(k)

def stringFunction(s1, s2):
    l1=list(''.join(s1.split()))
    l2=list(''.join(s2.split()))
    return [x for x in l1 if x in l2]

    print (stringFunction)

def longest_common_substring(s1, s2):
   set1 = set(s1[begin:end] for (begin, end) in
              itertools.combinations(range(len(s1)+1), 2))
   set2 = set(s2[begin:end] for (begin, end) in
              itertools.combinations(range(len(s2)+1), 2))
   common = set1.intersection(set2)
   return str(common)

main()

输出应该看起来像

1 个答案:

答案 0 :(得分:0)

你走了:

@ EDIT1:忘了在python3.x中打印是一个函数。

@ EDIT2:这不是原始请求的一部分。

@ EDIT3:将输出格式化为后面的请求(我不是打印格式的专家)。

@ EDIT4:修改输出以匹配修改后的请求

import string

def func(str1, str2):
    s1 = set(str1)
    s2 = set(str2)
    # requests are ambiguous "contained in both strings" can be either interpreted as intersections or union (i chose intersection)
    uni = s1.union(s2)
    letters_in_both_strings = [item for item in s1.intersection(s2) if item.isalpha()]
    non_letters_in_any_string = [item for item in uni if not item.isalpha()]
    all_letters = set(string.ascii_uppercase + string.ascii_lowercase)
    return letters_in_both_strings, all_letters.difference(uni), non_letters_in_any_string

str1 = input("Enter 1st string:")
str2 = input("Enter 2nd string:")
a, b, c = func(str1, str2)
print("|" + "".join(a) + "|\n|" + "".join(b) + "|\n|" + "".join(c) + "|\n")