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

I'm looking for a way to test whether or not a given string repeats itself for the entire string or not.


        '0045662100456621004566210045662100456621',             # '00456621'
        '0072992700729927007299270072992700729927',             # '00729927'
        '001443001443001443001443001443001443001443',           # '001443'
        '037037037037037037037037037037037037037037037',        # '037'
        '047619047619047619047619047619047619047619',           # '047619'
        '002457002457002457002457002457002457002457',           # '002457'
        '001221001221001221001221001221001221001221',           # '001221'
        '001230012300123001230012300123001230012300123',        # '00123'
        '0013947001394700139470013947001394700139470013947',    # '0013947'
        '001001001001001001001001001001001001001001001001001',  # '001'
        '001406469760900140646976090014064697609',              # '0014064697609'

are strings which repeat themselves, and


are examples of ones that do not.

The repeating sections of the strings I'm given can be quite long, and the strings themselves can be 500 or more characters, so looping through each character trying to build a pattern then checking the pattern vs the rest of the string seems awful slow. Multiply that by potentially hundreds of strings and I can't see any intuitive solution.

I've looked into regexes a bit and they seem good for when you know what you're looking for, or at least the length of the pattern you're looking for. Unfortunately, I know neither.

How can I tell if a string is repeating itself and if it is, what the shortest repeating subsequence is?

Here's a concise solution which avoids regular expressions and slow in-Python loops:

    def principal_period(s):
        i = (s+s).find(s, 1, -1)
        return None if i == -1 else s[:i]

See the Community Wiki answer started by @davidism for benchmark results. In summary,

David Zhang's solution is the clear winner, outperforming all others by at least 5x for the large example set.

(That answer's words, not mine.)

This is based on the observation that a string is periodic if and only if it is equal to a nontrivial rotation of itself. Kudos to @AleksiTorhamo for realizing that we can then recover the principal period from the index of the first occurrence of s in (s+s)[1:-1], and for informing me of the optional start and end arguments of Python's string.find.


Back to homepage or read more recommendations: