📜  Python程序检查重叠前缀 - 两个列表中的后缀

📅  最后修改于: 2022-05-13 01:54:19.781000             🧑  作者: Mango

Python程序检查重叠前缀 - 两个列表中的后缀

给定 2 个字符串,我们的任务是检查一个字符串的后缀与另一个字符串的前缀是否重叠。

Input : test_str1 = "Gfgisbest", test_str2 = "bestforall"
Output : best

Explanation : best overlaps as suffix of first string and prefix of next.

Input : test_str1 = "Gfgisbest", test_str2 = "restforall"
Output : ''

Explanation : No overlapping.

方法:使用循环+切片+ startswith()

在这里,我们增加第一个列表和切片直到列表结束,并使用startswith()与其他字符串的前缀子字符串进行比较。在这种情况下,出现在字符串末尾的单词与第二个字符串的前缀进行一次比较。

Python3
# Python3 code to demonstrate working of
# Overlapping Prefix - Suffix in Two Lists
# Using loop + slicing + startswith()
import re
  
# initializing strings
test_str1 = "Gfgisbest"
test_str2 = "bestforall"
  
# printing original strings
print("The original string 1 is : " + str(test_str1))
print("The original string 2 is : " + str(test_str2))
  
res = ''
for char in range(len(test_str1)):
      
    # using startswith() to get prefix
    if test_str2.startswith(test_str1[char:]):
        res = test_str1[char:]
        break
  
# printing result
print("Overlapped String  : " + str(res))


输出:

The original string 1 is : Gfgisbest
The original string 2 is : bestforall
Overlapped String  : best