Concepts / String Slicing and Indexing

String Slicing and Indexing

String reversal uses the slice notation [::-1] to read characters backward.

  • Programming

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.

python
Output
level
::-1thenthenthenthenleveloriginal orderlread firsteread secondvread thirderead fourthlread fifth
How does [::-1] read the characters from the last character to the first?

Tracing 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.

[::-1][::-1]pythonoriginalnohtypreversednoonoriginalnoonreversed
Which character order does the reverse slice include for each example string?

Reversing a Word

Determine the value returned by reverse when the input is "racecar".

Receive the original: The reverse function receives the string "racecar".

Apply the slice: The expression text[::-1] reads the characters from the last character toward the first.

Produce 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"))

========racecaroriginalTrueequalracecarreversedFalsenot equalpythonoriginalnohtypreversed
How does equality between the original and reversed strings determine the palindrome result?

Following 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.

python
capturepass textreturn backwardTrue or Falsekeyboard inputuser types textsomethingcaptured stringreverseapply [::-1]text == backwardcompare valuesprinted messagebased on True or False
How does typed input move from capture to reversal, comparison, and the final result?
Output
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.

pass captured textreturn reversed textevaluate equalitysomethingcaptured valuebackwardreversed valuetext == backwardcomparisonTrue or Falseactual result
At which step does the actual value differ from the value you expected?
  • Assuming the program compared the text you intended instead of the text you actually entered.

    The palindrome checker processes the value captured from the keyboard.

    Fix: Trace the value of something before checking the reverse and the comparison.

  • Checking only the reversed value and not the equality comparison.

    Palindrome detection depends on comparing the original and reversed strings with ==.

    Fix: Inspect both values used in text == backward.

  • Looking only at the final printed message during debugging.

    The final message does not show where the value changed or differed from your expectation.

    Fix: Follow the value from input capture, through reverse, to the comparison result.

Practice the Complete Flow

MEDIUM

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_palindrome call reverse and compare the returned value with the original text.
  • Store the keyboard input in a variable before passing it to is_palindrome.
EASY

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_input captures 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_input captures 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.