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
希望这对您有所帮助,并祝您有美好的一天,
安东尼诺
,
将set
与str.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