Editor

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 lesson

Write 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.)

def rotate(text, n):
pass
Solution unlocks after your first Check

What Check runs

Your code runs first, then each of these lines, and 5 more that stay hidden. The output must match exactly.

RunsExpected output
rotate("python", 2)'thonpy'
rotate("abc", -1)'cab'

More Strings exercises

All Python exercises · 50 practice problems · Python Fundamentals quiz