Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

python find repeated substring in string [closed]

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.

For example:

"pythonpythonp" => "python"

"hellohello" => "hello"

"appleapl" => "apple"

"spoon" => "spoon"

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

like image 820
Sieglinde Avatar asked Dec 10 '16 15:12

Sieglinde


People also ask

How do you check for repeated substrings in a string in Python?

(1) First generate the possible sub-strings you want to search in each string. Is there a min or max length? Build a list or set of sub-strings from the input string. (2) Once you have the sub-strings to search for, try to identify the unique locations within the input string where the substrings appear.

How do you pull a substring in Python?

You can extract a substring in the range start <= x < stop with [start:step] . If start is omitted, the range is from the beginning, and if end is omitted, the range is to the end. You can also use negative values. If start > end , no error is raised and an empty character '' is extracted.


1 Answers

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

Here's the code:

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")
like image 170
Tom Fuller Avatar answered Oct 12 '22 23:10

Tom Fuller