python在字符串中查找重复的子串 [英] python find repeated substring in string

查看:68
本文介绍了python在字符串中查找重复的子串的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在 Python 中寻找一个函数,您可以在其中输入一个字符串作为输入,其中某个单词已重复多次,直到达到某个长度.

I am looking for a function in Python where you give a string as input where a certain word has been repeated several times until a certain length has reached.

输出就是那个词.重复的单词没有必要全部重复,也有可能根本没有重复.

The output would then be that word. The repeated word isn't necessary repeated in its whole and it is also possible that it hasn't been repeated at all.

例如:

"pythonpythonp" => "python"

"hellohello" => "hello"

"appleapl" => "apple"

"spoon" => "spoon"

谁能给我一些关于如何编写这种函数的提示?

Can someone give me some hints on how to write this kind of function?

推荐答案

您可以通过将子字符串重复一定次数并测试它是否等于原始字符串来实现.

You can do it by repeating the substring a certain number of times and testing if it is equal to the original string.

除非您将其保存为变量,否则您必须为每个可能的字符串长度尝试它

You'll have to try it for every single possible length of string unless you have that saved as a variable

代码如下:

def repeats(string):
    for x in range(1, len(string)):
        substring = string[:x]

        if substring * (len(string)//len(substring))+(substring[:len(string)%len(substring)]) == string:
            print(substring)
            return "break"

    print(string)

repeats("pythonpytho")

这篇关于python在字符串中查找重复的子串的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆