String Rotation in Python

Check whether one string is a rotation of another.

IntermediateString ProgramsExample 17 of 25
string-rotation.py
Run in browser
1# Program to check if one string is a rotation of another
2
3s1 = input("Enter first string: ")
4s2 = input("Enter second string: ")
5
6if len(s1) != len(s2):
7 print("Not rotations (different lengths).")
8else:
9 if s2 in (s1 + s1):
10 print("Strings are rotations of each other.")
11 else:
12 print("Strings are not rotations of each other.")

Output

Enter first string: ABCD
Enter second string: CDAB
Strings are rotations of each other.

What's going on

If s2 is a rotation of s1, it must appear as a substring inside s1 + s1.