String Slicing and Indexing
String reversal uses the slice notation [::-1] to read characters backward.
Try it: Indexing and Slicing
How Python indexes a sequence from 0 (or from the end with negative numbers) and how a slice start:stop:step picks positions — with the exact CPython rules for omitted and out-of-range bounds.
How it works
- Positions run 0 … len−1; negative positions count back from the end (−1 is the last).
- An index outside the string raises IndexError.
- A slice resolves start and stop (omitted → the ends; out of range → clamped), then walks by step, stopping before stop.
- A negative step walks backwards; a step of 0 is a ValueError.
Default run (7 steps): 'PYTHONIC'[1:6:2]: a slice copies characters from start up to (not including) stop, moving by step. … 'PYTHONIC'[1:6:2] → 'YHN' (positions 1, 3, 5).
Simplified: Works on a short string (up to 16 printable ASCII characters); lists slice by exactly the same rules.
Loading the simulation…
A String Read Backward
String reversal means reading the characters in the opposite order. Python provides the slice notation [::-1] for this task. A palindrome detector uses that reversed string as evidence: it compares the original string with the reversed version. If the two values are equal, the text reads the same forwards and backwards.
levelTracing the Slice
The important part of [::-1] is its direction. Instead of preserving the original character order, it reads the string backward and produces a reversed version. For example, applying the slice to the source value "noon" produces "noon" again because the original and reversed orders happen to be identical. Applying it to "python" produces "nohtyp" because the characters are read in the opposite order.
Reversing a Word
Determine the value returned by reverse when the input is "racecar".
- 1Receive the original
The reverse function receives the string "racecar".
- 2Apply the slice
The expression text[::-1] reads the characters from the last character toward the first.
- 3Produce the result
Because "racecar" reads the same in both directions, the reversed value is also "racecar".
reverse("racecar") returns "racecar".
Comparing Palindromes
A palindrome is a word, phrase, or sequence that reads the same forwards and backwards. The checker can therefore be organized into two operations: reverse the original string, then compare the two strings with the equality operator. The comparison produces True when the original and reversed values are equal, and False when they are not.
def reverse(text):
return text[::-1]
def is_palindrome(text):
backward = reverse(text)
return text == backward
print(is_palindrome("racecar"))
print(is_palindrome("python"))- 1The reverse function receives a string and returns text[::-1].
- 2The
is_palindromefunction calls reverse and stores the returned value in backward. - 3The expression text == backward compares the original and reversed strings.
- 4The two print calls display the results for a palindrome and a non-palindrome.
- reverse returns the characters of text in reverse order.
is_palindromestores that reversed value in backward.- The equality comparison checks the original text against backward.
True
FalseFollowing User Input
raw_input pauses the program and waits for keyboard input. Whatever the user types becomes the value stored in a variable. That value can then flow into is_palindrome. The checker reverses it, compares the original and reversed versions, and returns True or False. An if statement uses that result to choose which message to print.
Enter text: level
The text is a palindrome.Debugging Divergent Results
When the program produces an unexpected result, trace the value of the input through every step. First check what raw_input stored in something. Next check the value returned by reverse. Finally check the two values used by the equality comparison. This step-by-step trace reveals the point where the actual result diverges from the expected result.
Common mistake Assuming the program compared the text you intended instead of the text you actually entered.
What it looks likeYou expect a result for one word, but raw_input stored a different word in something.
Why it failsThe palindrome checker processes the value captured from the keyboard.
Do this insteadTrace the value of something before checking the reverse and the comparison.
Common mistake Checking only the reversed value and not the equality comparison.
What it looks likeThe reverse function returns a value, but the final result is still unexpected.
Why it failsPalindrome detection depends on comparing the original and reversed strings with ==.
Do this insteadInspect both values used in text == backward.
Common mistake Looking only at the final printed message during debugging.
What it looks likeThe message says the text is not a palindrome, but the reason is unclear.
Why it failsThe final message does not show where the value changed or differed from your expectation.
Do this insteadFollow the value from input capture, through reverse, to the comparison result.
Practice the Complete Flow
Write a complete program that asks the user for text with raw_input, reverses the captured value with [::-1], compares the original and reversed strings with ==, and prints a message selected by an if statement. Test it with racecar, level, and noon.
Hints
- Put the slice expression inside a reverse function.
- Let
is_palindromecall reverse and compare the returned value with the original text. - Store the keyboard input in a variable before passing it to
is_palindrome.
Choose one test input for which you expect False. Trace the captured value, the reversed value, and the equality comparison before running the program.
Hints
- Choose text whose reverse is visibly different from the original.
- Write down the expected value at each stage of the program.
- The reverse function uses text[::-1] to read characters backward.
- The palindrome checker compares the original string with its reversed version using ==.
raw_inputcaptures keyboard input as a string and stores it in a variable.- The if statement chooses a message from the True or False result.
- Tracing each variable through the functions helps locate unexpected results.
Key Takeaways
- The slice [::-1] produces a string in reverse character order.
- A palindrome detector reverses the input and compares the original and reversed strings.
raw_inputcaptures the user's keyboard input as a string.- The comparison result, True or False, controls the final message.
- When results are unexpected, trace the input, reversed value, comparison, and printed decision in order.