keepcalculator

06 Numbers and Powers

Slice String Python: Syntax & Examples

Card No. 06·63436 · Updated · Standard formula, shown below

In Python, slicing a string extracts a substring by specifying a start and end index with the syntax string[start:end]. You get back a new string containing characters from start up to (but not including) end. This is one of the most frequently used operations in Python, essential for parsing text, cleaning data, and working with file names.

How String Indexing Works

Before slicing, you need to understand how Python numbers characters in a string. Every character has an index, starting at 0 for the first character. For the string s = "hello", the indices are:

  • s[0] → ‘h’
  • s[1] → ‘e’
  • s[2] → ‘l’
  • s[3] → ‘l’
  • s[4] → ‘o’

Python also supports negative indices, which count from the end. s[-1] is ‘o’, s[-2] is ‘l’, and so on. This is handy when you want the last few characters without knowing the string length.

The Slice Syntax: start, stop, step

The full slice syntax is string[start:stop:step]. All three parts are optional, but the colons are required if you want to use a later part. Here is what each part does:

  • start – the index where the slice begins (inclusive). If omitted, it defaults to 0.
  • stop – the index where the slice ends (exclusive). If omitted, it goes to the end of the string.
  • step – how many characters to jump after each one. Defaults to 1. A negative step reverses the direction.

For example, s[1:4] gives characters at indices 1, 2, and 3, so from “hello” you get “ell”. s[::2] takes every second character, giving “hlo”. s[::-1] reverses the string to “olleh”.

Common Slice Patterns

Certain slice patterns appear so often they are worth memorizing. Here are the most useful ones:

  • First n characters: s[:n] – e.g., "hello"[:2] → “he”
  • Last n characters: s[-n:] – e.g., "hello"[-2:] → “lo”
  • Everything except the first character: s[1:] – e.g., "hello"[1:] → “ello”
  • Everything except the last character: s[:-1] – e.g., "hello"[:-1] → “hell”
  • Reverse the string: s[::-1] – e.g., "hello"[::-1] → “olleh”
  • Every other character: s[::2] – e.g., "hello"[::2] → “hlo”

These patterns are the building blocks for more complex text processing, like extracting file extensions or trimming whitespace (though strip() is better for that).

Step and Negative Step Explained

The step parameter is often misunderstood. A step of 2 means “take one character, skip the next, take the next,” and so on. A negative step means you move backwards through the string. When the step is negative, the start and stop indices are interpreted in reverse order. For example, s[4:0:-1] on “hello” gives “oll” (indices 4, 3, 2, 1).

If you use a negative step, you usually want to omit start and stop to get the whole reversed string: s[::-1]. Trying to reverse a slice like s[0:4:-1] will return an empty string because you are asking to go backwards from index 0, which is already at the beginning.

Out-of-Range Indices and Empty Slices

Unlike indexing a single character (which raises an IndexError), slicing is forgiving. If your start or stop is beyond the string length, Python simply clamps it to the nearest valid index. For example, "hello"[0:100] returns “hello”, not an error. Similarly, "hello"[2:1] returns an empty string because the start is after the stop.

This behavior is useful when you do not know the exact length of the string. You can safely do s[:10] on a short string and get the whole thing. However, be careful when using negative indices with a step: s[-1:0:-1] gives everything except the first and last characters, which might not be what you expect.

Slice Assignment and Immutability

Strings in Python are immutable, meaning you cannot change a character in place. s[0] = 'j' raises a TypeError. Slicing does not modify the original string; it creates a new string. If you want to modify a string, you must create a new one, for example: s = s[0] + 'j' + s[2:].

There is a similar syntax for lists that does allow assignment, like my_list[1:3] = [9, 8], but that works only on mutable sequences. For strings, always remember that any slice operation returns a new string, leaving the original untouched.

Practical Examples and Use Cases

Slicing is used everywhere in real-world Python code. Here are a few concrete examples:

  • Extracting a file extension: filename[-3:] gives the last three characters (e.g., “pdf” from “report.pdf”).
  • Removing a prefix: url[8:] on “https://example.com” gives “example.com” (assuming you know the prefix length).
  • Parsing fixed-width data: line[10:20] extracts characters 10 to 19, useful for columns in old data files.
  • Checking a palindrome: s == s[::-1] tests if a string reads the same forward and backward.
  • Truncating text: text[:100] + "..." gives a short preview of a long string.

These are just a few of the countless applications. Once you get comfortable with slicing, you will find yourself reaching for it constantly.

Frequently Asked Questions

What does s[::-1] do?

It reverses the string. The empty start and stop mean “the whole string,” and the step of -1 means “go backwards one character at a time.” So "abc"[::-1] returns “cba”.

Why does s[0:3] not include the character at index 3?

Because the stop index is exclusive. This is a common Python convention that makes slices behave predictably: s[:3] and s[3:] together cover the entire string without overlapping or leaving a gap. It also matches how range(0, 3) works in loops.

Can I slice a string with a variable step?

Yes, the step can be any integer, positive or negative. For example, s[::3] takes every third character. You can also use a variable: step = 2; s[::step].

What happens if I use a step of 0?

You get a ValueError: slice step cannot be zero. A step of zero makes no sense because you would never move forward. Python raises an error to prevent an infinite loop.

Is there a performance difference between slicing and other methods?

Slicing creates a new string, which takes time and memory proportional to the length of the slice. For very large strings, this can be slower than using methods like find() or startswith() if you only need to check something. But for most tasks, slicing is fast and idiomatic.

How do I slice a string from the end to a specific point?

Use negative indices. For example, s[-5:-2] gives the characters from the fifth-from-last to the third-from-last (exclusive). To get the last three characters, use s[-3:]. To get everything except the last two, use s[:-2].

Related

Method: the standard formula for this calculation, rounded as each result states. See how the calculators work or report an error.

More cards in this drawer

The whole Numbers and Powers drawer →