← Back to Blog

Take a Piece of the String

The problem...

You know how to get one character from a string.

But what if you need more than one?

A word from a sentence. A piece of a code. A chunk of text.

One index isn't enough.

The idea!

Python lets you grab a range of characters from a string.

This is called slicing.

Making it real

Think of it like this: you have a row of seats. You don't want just one. You want seats 2 through 5.

Slicing does exactly that — you tell Python where to start and where to stop.

In practice

name = "RedHorn"
print(name[0:3])

Output → Red

The syntax is [start:stop].

Start is included. Stop is not.

The full picture

name = "RedHorn"
#       R e d H o r n
#       0 1 2 3 4 5 6
  • name[0:3]Red
  • name[3:7]Horn
  • name[0:7]RedHorn

Going further

You can leave out the start or the stop. Python fills in the rest.

name = "RedHorn"
print(name[:3])
print(name[3:])

Output → Red

Output → Horn

[:3] means from the beginning to position 3.

[3:] means from position 3 to the end.

What's really happening

You're not copying the string. You're telling Python exactly which part you want.

Python reads that range and returns it as a new string.

Heads up!

  • The stop index is not included — [0:3] gives you positions 0, 1, 2
  • If your start is bigger than your stop, you get an empty string — no error
  • Slicing never modifies the original string
  • The full syntax is [start:stop:step] — but step is advanced, you don't need it now

The mindset shift

Stop thinking: "I need the whole string or nothing."

Start thinking: "I can take exactly the piece I need."

What you should understand now

  • Slicing extracts a range of characters from a string
  • Syntax is [start:stop]
  • Start is included, stop is not
  • You can omit start or stop — Python fills in the rest
  • The original string is never changed
[ login to bookmark ] // copied! 50 views · 1 min
// resources
Code Example strings_slicing.py
← prev Every Character Has a Number next → Methods — Your String’s Toolkit
// 0 comments
// No comments yet. Be the first.
// leave a comment

// Your comment will appear after approval.