String Rotation in Python

Check whether one string is a rotation of another.

IntermediateString ProgramsExample 17 of 25
string-rotation.py
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.

After this program

If the idea is still fuzzy, read Day 4: Strings and String Methods in the Python course. For a short check, try the Python quiz (300 questions). Stay with all 25 string programs, or see every topic on Python exercises.