Concepts / String Slicing and Indexing

String Slicing and Indexing

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

  • Programming
Interactive lab

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

  1. Positions run 0 … len−1; negative positions count back from the end (−1 is the last).
  2. An index outside the string raises IndexError.
  3. A slice resolves start and stop (omitted → the ends; out of range → clamped), then walks by step, stopping before stop.
  4. 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.

Educational simulation

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.

python
Output
level
leveloriginal orderlread firsteread secondvread thirderead fourthlread fifth::-1thenthenthenthen
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.

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

Reversing a Word

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

  1. 1
    Receive the original

    The reverse function receives the string "racecar".

  2. 2
    Apply the slice

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

  3. 3
    Produce the result

    Because "racecar" reads the same in both directions, the reversed value is also "racecar".

Result

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.

Code walkthrough
def reverse(text):
    return text[::-1]

def is_palindrome(text):
    backward = reverse(text)
    return text == backward

print(is_palindrome("racecar"))
print(is_palindrome("python"))
  1. 1
    The reverse function receives a string and returns text[::-1].
  2. 2
    The is_palindrome function calls reverse and stores the returned value in backward.
  3. 3
    The expression text == backward compares the original and reversed strings.
  4. 4
    The two print calls display the results for a palindrome and a non-palindrome.
  • reverse returns the characters of text in reverse order.
  • is_palindrome stores that reversed value in backward.
  • The equality comparison checks the original text against backward.
Output
True
False
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
keyboard inputuser types textsomethingcaptured stringreverseapply [::-1]text == backwardcompare valuesprinted messagebased on True or Falsecapturepass textreturn backwardTrue 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.

somethingcaptured valuebackwardreversed valuetext == backwardcomparisonTrue or Falseactual resultpass captured textreturn reversed textevaluate equality
At which step does the actual value differ from the value you expected?
  • Common mistake

    Assuming the program compared the text you intended instead of the text you actually entered.

    What it looks like

    You expect a result for one word, but raw_input stored a different word in something.

    Why it fails

    The palindrome checker processes the value captured from the keyboard.

    Do this instead

    Trace 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 like

    The reverse function returns a value, but the final result is still unexpected.

    Why it fails

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

    Do this instead

    Inspect both values used in text == backward.

  • Common mistake

    Looking only at the final printed message during debugging.

    What it looks like

    The message says the text is not a palindrome, but the reason is unclear.

    Why it fails

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

    Do this instead

    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.

Related concepts

More concepts starting with S