Computer >> Hướng Dẫn Máy Tính >  >> Lập Trình >> Python

Kiểm tra string lặp lại chính nó trong Python

Muốn check xem string có compose bằng lặp lại substring của chính nó. Check bằng cách xem rotation của string có tồn tại trong concatenation 2 string. Vì string periodic nếu và chỉ nếu nó bằng nontrivial rotation của chính nó.

Ví dụ

Code sau check và trả về:

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')

Output

012
None