Rotate the Letters
Advanced · Stretch · from Python Strings: Create, Access, Slice, and Manipulate Text
From the lesson: Python Strings: Create, Access, Slice, and Manipulate Text
Think about your phone. Almost everything you see on the screen is text: names in your contacts, messages from friends, search results, notifications. Behind the scenes, all of that text is handled by strings.
Read the lessonWrite a function rotate(text, n) that moves the first n characters of text to the end. A negative n rotates the other way: the last characters move to the front.
rotate("python", 2) # 'thonpy'
rotate("python", -1) # 'npytho'
rotate("python", 6) # 'python' (a full turn)n can be bigger than the length of the text, in either direction: rotating "python" by 8 is a full turn plus 2 more. text always has at least one character.
The def line is written for you: put your code under it, indented four spaces, and end with return and your answer. Check calls rotate() with its own words, some of them hidden. (Functions get their own lesson later.)
What Check runs
Your code runs first, then each of these lines, and 5 more that stay hidden. The output must match exactly.
| Runs | Expected output |
|---|---|
| rotate("python", 2) | 'thonpy' |
| rotate("abc", -1) | 'cab' |
More Strings exercises
- Build a Greeting with ConcatenationBeginner
- Get the First and Last CharacterBeginner
- Reverse a StringBeginner
- Predict the Slice OutputBeginner
- Fix the Bug: Mutating a StringBeginner
- Check If a Word Is in a SentenceBeginner
- Extract a Domain from an Email AddressBeginner
All Python exercises · 50 practice problems · Python Fundamentals quiz