How can I tell if a string repeats itself in Python?

PythonServer Side ProgrammingProgramming

We want to check whether the string we have is composed of repetitions of a substring of this string only. To check that we can check if a rotation of the string exists in a combination of 2 strings. This is because a string is periodic if and only if it is equal to a nontrivial rotation of itself.


The following code checks this and returns accordingly:

def find_period(s):
    # Concatenate 2 s and find s within
    # index one to end of the string
    i = (s+s).find(s, 1, -1)
    return None if i == -1 else s[:i]
print find_period('012012012012012')
print find_period('some random string')


This will give us the output:

Published on 18-Dec-2017 13:23:44