如何判断Python中的字符串是否重复
在本文中,我们将探讨如何判断Python中的字符串是否重复。
第一种方法是使用切片和 find() 函数。我们希望看到我们拥有的字符串是否完全由一个子串的重复组成。我们可以通过在一对字符串中查找字符串的旋转来确认这一点。
在添加一个字符串并检查该字符串中的根字符串之后,除了最后和第一个字符之外,我们可以搜索根字符串。这种方法对长度小于2的字符串不起作用。
示例1
在下面给出的示例中,我们输入一个字符串并使用切片和 find() 方法来检查它是否重复。
def find_period(s):
i = (s+s).find(s, 1, -1)
return None if i == -1 else s[:i]
str1 = '012012012012012'
print("The given string is")
print(str1)
print("Checking if any substring that is repeating")
res = find_period(str1)
print(res)
输出
以上示例的输出如下所示−
The given string is
012012012012012
Checking if any substring that is repeating
012
示例2
在下面的示例中,我们使用与上述相同的程序,但我们采用不同的输入并检查它是否重复。
def find_period(s):
i = (s+s).find(s, 1, -1)
return None if i == -1 else s[:i]
str1 = 'abcdefgh'
print("The given string is")
print(str1)
print("Checking if any substring that is repeating")
res = find_period(str1)
print(res)
输出
上面示例的输出如下所示 –
The given string is
abcdefgh
Checking if any substring that is repeating
None
使用暴力破解方法
第二种方法是暴力破解方法,我们将不断迭代字符串并检查重复的序列。这项工作可以通过选择性切片和暴力破解方法来实现。这是一种原始的字符串发现方法,我们试图通过反复划分字符串来识别根字符串。
示例
在下面给出的示例中,我们以字符串作为输入,并使用列表推导式检查字符串的任何部分是否重复。-
str1 = '012012012012012'
print("The given string is")
print(str1)
print("Checking if any substring that is repeating")
res = None
for i in range(1, len(str1)//2 + 1):
if (not len(str1) % len(str1[0:i]) and str1[0:i] *(len(str1)//len(str1[0:i])) == str1):
res = str1[0:i]
print(res)
输出
上面示例的输出如下所示−
The given string is
012012012012012
Checking if any substring that is repeating
012