Concepts / String Operations and Slicing

String Operations and Slicing

raw_input() captures text from the keyboard and returns it as a string to your program.

  • 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…

From Keyboard to Variable

A program can receive text from outside itself through raw_input(). This function displays a prompt, waits for the user to type text and press Enter, and returns the entered text as a string. When that returned value is assigned to a variable, the rest of the program can process it.

Keyboardtyped textPromptdisplayed firstraw_input()waits and returns textString valuereturned textsomethingstored responseProcessingprogram logicshown before waitingtext and Enterreturnsassigned toused by
How does text typed at the keyboard move through raw_input(), become a string value, and reach the variable used by the program?
python
  1. 1
    The prompt string is displayed.
  2. 2
    The program waits for the user.
  3. 3
    The user types text and presses Enter.
  4. 4
    raw_input() captures and returns that text.
  5. 5
    The returned string is stored in something.

Strings Through Program Logic

After raw_input() returns, the response is available as a string value. The program can pass that string to other operations and functions. In the palindrome example, the entered text is passed to a checking function. That function compares the original text with a reversed version. If both versions match, the text is a palindrome.

Definition

A palindrome is a word or phrase that reads the same forwards and backwards.

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

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

text = raw_input("Enter text: ")
result = is_palindrome(text)
print result
  1. 1
    reverse() receives a string and returns that string in reverse order.
  2. 2
    is_palindrome() calls reverse() and compares the returned value with the original text.
  3. 3
    The main program asks for text and stores the response in text.
  4. 4
    The response is passed into is_palindrome(), and the returned result is stored in result.
  5. 5
    The program prints the result of the comparison.
  • reverse() uses [::-1] to flip the string backwards.
  • is_palindrome() compares the original string with its reversed version.
  • raw_input() captures the user's text.
  • The response is passed to is_palindrome().
  • The result is printed.

Reversing with Slice Notation

The palindrome check depends on the slice notation [::-1]. In this program, that notation flips the string backwards. The important comparison is between two values: the original text and the reversed text. Matching values indicate a palindrome; different values indicate that the entered text does not read the same forwards and backwards.

leveloriginal textleveltext[::-1][::-1]
Which character order is compared when [::-1] reverses a string?
Worked example

Tracing a palindrome response

A user enters text, and the program must determine whether the text is a palindrome.

  1. 1
    Input capture

    raw_input() displays the prompt, waits for the response, and returns the entered text as a string.

  2. 2
    Reversal

    reverse() applies [::-1] to produce the text in backward order.

  3. 3
    Comparison

    is_palindrome() compares the original response with the reversed response.

  4. 4
    Decision result

    If the two strings match, the response is a palindrome.

Result

The program's result depends on the comparison between the captured string and its reversed version.

Finding the Divergence

When output is unexpected, do not inspect only the final result. Trace the program step by step and identify the state of the data at each major stage. For the palindrome checker, inspect input capture, palindrome checking, and output. This narrows the problem to the point where the actual result first differs from the expected result.

Input captureraw_input()Palindrome checkingoriginal versus reversedOutputprinted resultcaptured stringcomparison result
What happens to the input string as the program captures it, processes it, and produces its result?
  • Common mistake

    Treating the value returned by raw_input() as a number automatically.

    What it looks like

    A response captured by raw_input() is used directly for numeric operations.

    Why it fails

    raw_input() returns a string.

    Do this instead

    Convert the returned string to int or float when numeric operations are required.

  • Common mistake

    Debugging only the printed result.

    What it looks like

    The final palindrome result is unexpected, but the input and comparison stages are not inspected.

    Why it fails

    The divergence may have occurred during input capture, processing, or output.

    Do this instead

    Trace the execution step by step and inspect the data at each stage.

  • Common mistake

    Forgetting that the prompt, the typed response, and the returned string are different parts of the input process.

    What it looks like

    The displayed prompt is treated as though it were the user's response.

    Why it fails

    The prompt is displayed first; raw_input() then waits for the user to type text and returns that typed text.

    Do this instead

    Separate the prompt display, user entry, returned string, and variable assignment when tracing the program.

Practice the Trace

MEDIUM

Write down the value at each stage of a palindrome-checking program: the text entered by the user, the value returned by reverse(), the comparison performed by is_palindrome(), and the final printed result. Then identify which stage you would inspect first if the output did not match your expectation.

Hints
  • Begin with the fact that raw_input() returns a string.
  • Use [::-1] to represent the reversal stage.
  • Compare the original string with the reversed string before considering the printed output.
  1. 1
    Identify the prompt shown to the user.
  2. 2
    Record the text typed and returned by raw_input().
  3. 3
    Record the reversed value produced by [::-1].
  4. 4
    Compare the original and reversed values.
  5. 5
    Use the comparison result to explain the program's output.

Key Takeaways

  1. 1
    raw_input() displays a prompt, waits for keyboard input, and returns the entered text as a string.
  2. 2
    The returned string is stored in a variable and can then be passed through program logic.
  3. 3
    The slice notation [::-1] reverses a string, making it useful for comparing text with its backward form.
  4. 4
    A palindrome checker compares the original string with its reversed version.
  5. 5
    To debug unexpected output, trace input capture, processing, and output step by step.

At a glance

  • raw_input() captures keyboard text and returns it as a string.
  • The captured response can be stored, reversed with [::-1], and compared with the original.
  • A palindrome is detected when the original text and its reversed version match.
  • Tracing each program stage helps locate whether an unexpected result began during input, processing, or output.

Related concepts

More concepts starting with S