如何在 Python 中判断字符串是否自身重复?


在本文中,我们将了解如何在 Python 中判断字符串是否自身重复。

第一种方法是使用切片和find()函数。我们想要查看给定的字符串是否完全由其子字符串的重复构成。我们可以通过在一个字符串对中查找字符串的旋转来确认这一点。

在添加一个字符串并在该字符串中检查根字符串(除了最后一个和第一个字符)后,我们可以搜索根字符串。这种方法不适用于长度小于 2 的字符串。

示例 1

在下面给出的示例中,我们以字符串作为输入,并使用切片和find()方法检查它是否重复

Open Compiler
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

Learn Python in-depth with real-world projects through our Python certification course. Enroll and become a certified expert to boost your career.

示例 2

在下面给出的示例中,我们使用与上面相同的程序,但使用不同的输入并检查它是否重复

Open Compiler
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

使用暴力破解方法

第二种方法是暴力破解方法,我们将不断迭代字符串并检查重复序列。这项工作可以通过选择性切片和暴力破解方法来完成。这是一种原始的字符串发现方法,我们尝试通过重复划分字符串来识别根字符串。

示例

在下面给出的示例中,我们以字符串作为输入,并使用列表推导式检查字符串的任何部分是否重复

Open Compiler
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

更新于: 2022-12-07

1K+ 次查看

开启你的 职业生涯

通过完成课程获得认证

开始学习
广告