Start learning free

LESSON 61 OF 410 · STRINGS I

String Slicing in Python

Lesson Read the full explanation

Not only we can select a single character from a string, but we can also select a sequence of consecutive characters (e.g. substring) from a string.

To achieve this, we use the the following syntax:

string[startIndex:endIndex]

This is called slicing a string. It returns the substring from startIndex to endIndex.

Here is an example:

language = "JavaScript"
substring = language[2:6]

print(substring) # Output: "vaSc"
print(language) # Output: "JavaScript"

The startIndex is a zero-based index at which we start extraction and the endIndex is also zero-based index before which we end the extraction.

The substring will not include the character at endIndex. You can see in our example that language[2] (v) was included while language[6] (r) was excluded.

Also notice that language preserved its value. The slicing does not affect the original string. It just creates a brand new one representing the sliced substring.


If you omit the endIndex, the slicing extracts to the end of the string:

language = "JavaScript"
substring = language[4:]

print(substring) # Output: "Script"

If you omit the startIndex, the slicing extracts from the start of the string:

language = "JavaScript"
substring = language[:4]

print(substring) # Output: "Java"

If you omit both startIndex and endIndex, the slicing extracts from the start to the end of the string. It basically clones the string:

language = "JavaScript"
substring = language[:]

print(substring) # Output: "JavaScript"


Assignment
Follow the Coding Tutorial and let's slice some strings!


Hint
Look at the examples above if you get stuck.


STEP 1 OF 3
    Ctrl + Enter to check

    PYTHON · STRINGS I

    String Slicing in Python, explained

    Python String Slicing: Extract Any Substring with s[start:stop:step]

    Slicing is one of Python's most powerful and distinctive features. With a single expression you can grab the first N characters of a string, reverse it entirely, extract every other letter, or pull a substring from the middle — all without a loop. It's used constantly in real code: trimming titles, parsing file extensions, extracting URL segments, and implementing algorithms. Once it clicks, you'll use it every day.

    Visualising the Indices

    Think of the indices as sitting between characters, not on them. s[2:6] cuts at position 2 and position 6:

    s = "JavaScript"
    #    J  a  v  a  S  c  r  i  p  t
    #    0  1  2  3  4  5  6  7  8  9   ← positive indices
    #  -10 -9 -8 -7 -6 -5 -4 -3 -2 -1  ← negative indices
    
    print(s[2:6])   # "vaSc"  — positions 2,3,4,5 (6 is excluded)
    print(s[:4])    # "Java"  — from start up to (not including) 4
    print(s[4:])    # "Script" — from 4 to the end
    

    The Three-Part Syntax: start:stop:step

    s = "Python"
    
    # Basic: s[start:stop]
    print(s[1:4])    # "yth"   — indices 1, 2, 3
    
    # Omit start → defaults to 0
    print(s[:3])     # "Pyt"
    
    # Omit stop → defaults to len(s)
    print(s[3:])     # "hon"
    
    # Omit both → copy of the whole string
    print(s[:])      # "Python"
    
    # With step: s[start:stop:step]
    print(s[::2])    # "Pto"   — every 2nd character
    print(s[1::2])   # "yhn"   — every 2nd starting at index 1
    

    Negative Indices: Count from the End

    Negative indices count backward from the end of the string. -1 is the last character, -2 is second-to-last, and so on:

    s = "Python"
    
    print(s[-1])     # "n"      — last character
    print(s[-3:])    # "hon"    — last 3 characters
    print(s[:-3])    # "Pyt"    — everything except the last 3
    print(s[-4:-1])  # "tho"    — inner slice using negative indices
    

    Reversing a String with [::-1]

    A step of -1 walks backward through the string. This is the idiomatic Python way to reverse a string — no loop needed:

    s = "Python"
    print(s[::-1])   # "nohtyP"
    
    # Useful in interview problems:
    word = "racecar"
    print(word == word[::-1])   # True — it's a palindrome
    

    Out-of-Bounds Indices Don't Crash

    Unlike indexing a single character, slicing never raises an IndexError — Python clips the indices to valid bounds:

    s = "Hi"
    print(s[0:100])   # "Hi"   — not an error, just clips to len(s)
    print(s[5:10])    # ""     — empty string, start is already past the end
    print(s[-100:])   # "Hi"   — clips to the start of the string
    

    Real-World Patterns

    # Get file extension:
    filename = "report_2024.pdf"
    extension = filename[-3:]         # "pdf"
    
    # Truncate a title for a preview card:
    title = "Introduction to Machine Learning Algorithms"
    preview = title[:30] + "..."      # "Introduction to Machine Learnin..."
    
    # Extract domain from a URL path:
    url = "https://example.com/blog/post-1"
    path = url[url.index("/", 8):]    # "/blog/post-1"
    
    # Check if a string starts with a prefix (manual version):
    s = "Hello, world"
    print(s[:5] == "Hello")           # True
    

    Slicing vs. Indexing: Key Difference

    • s[i] — returns a single character; raises IndexError if out of range.
    • s[i:j] — returns a string (possibly empty); never raises IndexError.
    • Slices always return a new string — the original is unchanged (strings are immutable).

    Key Takeaways

    • s[start:stop] — start is inclusive, stop is exclusive.
    • Omit start for "from beginning", omit stop for "to end", omit both to copy.
    • Negative indices count from the end: s[-1] is the last character.
    • s[::-1] reverses a string — the most common step-slice in practice.
    • Out-of-range indices in slices never crash — Python clips them silently.

    What to Learn Next

    String slicing is the foundation for many string operations. Next, explore string methods that combine well with slicing: find() and index() to locate where to slice, split() to break strings into lists, and join() to reassemble them. In algorithm problems, slicing is fundamental to palindrome checking, anagram detection, and sliding window problems.

    Keep going with PythonAbout 340 step-by-step lessons, from your first line of code to coding interviews. Free to start.
    Start learning free