如何从python中的另一个字符串检测字符串的重复元素? 输出

那么我将如何使用python的另一条字符串来查找字符串的重复元素,而该字符串大部分是一到两行还是快速修复?

例如

str1 = "abccde"
str2 = "abcde"
# gets me c

通过使用str2,发现str1中存在重复元素,因此检测到str1中存在str2中元素的重复。不确定是否可以通过.count完成此操作,例如str1.count(str2)之类的东西。

我在为子手分配内容时使用此上下文,并且我是一名初学者,因此我们主要使用内置函数和分配的基础知识,并且在循环中有一部分代码可以保持打印,因为它会出现两个字母。

例如你好,研磨,混合。

所以我几乎做了一个“用过的”字符串,我试图将它与我的正确字母列表进行比较,并且猜测被“附加”了,所以我可以避免这种情况。

请注意:它们会被输入,因此我无法说出或仅对字母c进行硬编码。

谢谢!

aa469011586 回答:如何从python中的另一个字符串检测字符串的重复元素? 输出

Ciao

您基本上是在两个字符串之间搜索diff函数。调整this beautiful answer

import difflib

cases=[('abcccde','abcde')] 

for a,b in cases:     
    print('{} => {}'.format(a,b))  
    for i,s in enumerate(difflib.ndiff(a,b)):
        if s[0]==' ': continue
        elif s[0]=='-':
            print(u'The second string is missing the "{}" in position {} of the first string'.format(s[-1],i))
        elif s[0]=='+':
            print(u'The first string is missing the "{}" in position {} of the second string'.format(s[-1],i))    
    print() 

输出

abcccde => abcde
The second string is missing the "c" in position 3 of the first string
The second string is missing the "c" in position 4 of the first string

希望这对您有所帮助,并祝您有美好的一天,
安东尼诺

,

setstr.count一起使用:

def find_dup(str1,str2):
    return [i for i in set(str1) if str1.count(i) > 1 and i in set(str2)]

输出:

find_dup("abccde","abcde")
# ['c']
find_dup("abcdeffghi","aaaaaabbbbbbcccccddeeeeefffffggghhiii") # from comment
# ['f']
,

我的猜测是,也许您正在尝试编写类似于以下内容的方法:

def duplicate_string(str1: str,str2: str) -> str:
    str2_set = set(str2)
    if len(str2_set) != len(str2):
        raise ValueError(f'{str2} has duplicate!')

    output = ''
    for char in str1:
        if char in str2_set:
            str2_set.remove(char)
        else:
            output += char

    return output


str1 = "abccccde"
str2 = "abcde"

print(duplicate_string(str1,str2))

输出

ccc

在这里,如果str2本身有重复项,我们将首先提出一个错误。然后,我们将遍历str1,或者从str1_set中删除一个字符,或者将重复项附加到output字符串中。

本文链接:https://www.f2er.com/3169540.html

大家都在问