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

后端 未结 13 1468
栀梦
栀梦 2020-11-27 09:07

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

Examples:

[
    \'0045662100456621004566210         


        
13条回答
  •  孤独总比滥情好
    2020-11-27 09:25

    This version tries only those candidate sequence lengths that are factors of the string length; and uses the * operator to build a full-length string from the candidate sequence:

    def get_shortest_repeat(string):
        length = len(string)
        for i in range(1, length // 2 + 1):
            if length % i:  # skip non-factors early
                continue
    
            candidate = string[:i]
            if string == candidate * (length // i):
                return candidate
    
        return None
    

    Thanks to TigerhawkT3 for noticing that length // 2 without + 1 would fail to match the abab case.

提交回复
热议问题