Check String Rotation
Check whether one string is a rotation of another with Python. Students require equal lengths and search the doubled first string for a wrapped arrangement.
1# Take two strings2s1 = input("Enter first string: ")3s2 = input("Enter second string: ")45# Check rotation6if len(s1) == len(s2):7 # Concatenate s1 with itself8 temp = s1 + s19 if s2 in temp:10 print("Rotation")11 else:12 print("Not a rotation")13else:14 print("Not a rotation (different lengths)")
Output
Enter first string: hello Enter second string: lohel Rotation
In this one
- Preserve rotation length
- Search doubled text
- Allow zero-position rotation
How it works
- 1
Compare the two string lengths.
- 2
When equal, build s1 + s1.
- 3
Test membership of s2 and print the rotation decision.
Edge cases
Do identical strings count as rotations?
Do identical strings count as rotations?
Yes. A zero-position rotation is allowed.
Why compare lengths first?
Why compare lengths first?
A rotation preserves the number of characters.
What's going on
Joining s1 to itself makes every cyclic starting point appear as a contiguous substring. The length guard ensures s2 represents a full rotation, not a shorter fragment.
For abcd and cdab, the doubled text abcdabcd contains cdab. This allows a zero-position rotation, so identical strings pass. Matching is exact and case-sensitive; even two empty strings pass the length and substring checks.
Do identical strings count as rotations? Yes. A zero-position rotation is allowed.
Why compare lengths first? A rotation preserves the number of characters.
Quiz
Tap an option. The answer stays hidden until you pick.
Question 1
Which construction supports wrapped matches?
Pick an answer to check it.
Question 2
Do identical strings count as rotations?
Pick an answer to check it.
Questions people ask
Do identical strings count as rotations?
Yes. A zero-position rotation is allowed.
Why compare lengths first?
A rotation preserves the number of characters.
Which construction supports wrapped matches?
s1 + s1.
๐Related Content
- ๐
Phase 5 - Learn Concepts
Review Phase 5 concepts and explanations
- ๐
Phase 5 - Quiz
Test your Phase 5 understanding with quiz questions
- ๐ป
Phase 5 - All Practice Problems
Explore all practice problems for Phase 5
- ๐
Master Your Logic Building - Complete Course
Browse all phases and tutorials
- ๐ง
Logic Building Overview
Learn about the complete logic building curriculum