![](/img/trans.png)
[英]Is there a function in python to replace characters in a string and vice-versa?
[英]Given two strings, find if 5 characters or more of the first string is a section of the second and vice versa (Python)
Example input:
str1 = 'ZZZABCDEFRFR'
str2 = 'DDDDDDDDDDDDABCDERR'
Example output: True
Example input:
str1 = 'DDDDDDDDDDDDABACDERR'
str2 = 'ZZZABCDEFRFR'
Example output: False
我尝试了与此类似的方法,但它会跳过字符,直到找到一个匹配项。 这不是我想要的……
def issubsequence(s1, s2):
n,m = len(s1),len(s2)
i,j = 0,0
while (i < n and j < m):
if (s1[i] == s2[j]):
i += 1
j += 1
# If i reaches end of s1,that mean we found all
# characters of s1 in s2,
# so s1 is subsequence of s2, else not
return i == n
使用 for 循环遍历您的第一个字符串。 然后使用in
运算符检查第二个是否是 ZE83AED3DDF4667DEC0DAAAACB2BB3BE0BZ。 下面的代码检查 str1 是否在 str2 中。 您可以交换它们以检查其他方式。
for i in range(len(str1) - 4):
substr1 = str1[i:i+5]
if substr1 in str2:
print(f'{substr1} in {str2}')
您可以在两个字符串的切片上使用集合交集:
def f(s1,s2,len_=5):
if min(map(len, [s1,s2]))<len_: return False
return bool({s1[i:i+len_] for i in range(0,len(s1)-len_+1)} &
{s2[i:i+len_] for i in range(0,len(s2)-len_+1)})
测试它:
cases=[(True,'ZZZABCDEFRFR','DDDDDDDDDDDDABCDERR'),
(False,'DDDDDDDDDDDDABACDERR','ZZZABCDEFRFR'),
(True,'abcde','abcde'),
(True,'xabcde','yabcde')]
for b,x,y in cases:
print(b,x,y,f(x,y))
印刷:
True ZZZABCDEFRFR DDDDDDDDDDDDABCDERR True
False DDDDDDDDDDDDABACDERR ZZZABCDEFRFR False
True abcde abcde True
True xabcde yabcde True
或者,将next
与具有相同 substring 切片的生成器一起使用:
def f2(s1,s2,len_=5):
if min(map(len, [s1,s2]))<len_: return False
return next((True for i in range(0,len(s1)-len_+1)
if s1[i:i+len_] in s2), False)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.