Reverse a message
Difficulty: Easy
Try your first run
No account is needed to try this exercise. Write your answer, run the tests, and use the feedback to improve it.
- Read the examples and the required return value.
- Edit the supplied function in the editor, keeping its name and parameters. Return your answer, then select Run code.
- Use the test feedback to try again. Hints are available without replacing your code.
Return a new string containing the Unicode code points of s in reverse order. Preserve spaces, punctuation, and case; do not reverse only the order of words.
What this practices
Python strings are immutable sequences. This task connects sequence order to indexing and slicing: the final code point in the input becomes the first in the result. Return the string rather than printing it.
Work through an example
For "Go! ", the input ends with a space. The result is " !oG": the space moves to the front, followed by the exclamation mark, lowercase o, and uppercase G. No character is removed or normalized.
Edge cases to check
- An empty string returns an empty string.
- A single code point remains unchanged.
- Repeated characters still appear the same number of times.
- Leading and trailing whitespace participate in the reversal.
Python and Unicode
A Python string is indexed by Unicode code point, not by byte. A displayed character can contain several code points: "e\u0301" contains an e followed by a combining accent. This exercise reverses those two code points too; it does not promise to preserve grapheme clusters such as combined accents or emoji sequences.
Before running your code, predict the output for "ab ba". Then check that reversing twice restores the original string.
Examples
'abc''cba''''''a''a'Constraints
0–10,000 code points; reverse code points, not grapheme clusters.
Review lesson: Indexing and slicingA little nudge
Reveal one hint at a time. Give yourself a moment to try it.
- A slice can move backwards.
- Use a negative step.
Worked solution
Try your own approach first, then compare the reasoning.
def reverse_message(s):
return s[::-1]
A slice with step -1 reads the string from the end and constructs a new string. The original string is unchanged. Spaces and combining marks are sequence elements too, so this implements code-point reversal rather than word reversal or grapheme-aware text processing.
Complexity
O(n) time and O(n) output space for n Unicode code points.
Ready when you are
Write your solution, then run it against the practice tests.
Press Esc, then Tab to leave the editor. Code runs in an isolated browser workspace. Tests support learning, not verified grading.