Level 1
0 / 100 XP

Slicing and in

Sometimes you don't want the whole string — you want the first few characters, the last few, or just a middle chunk. Slicing lets you grab any part of a string by position. And the in operator lets you ask "does this text appear inside that text?"

Indexing: one character

Every character has a position called an index, starting at 0:

Python
s = "python" # 012345 print(s[0]) # p print(s[1]) # y print(s[-1]) # n (negative counts from the end)

Slicing: a range of characters

Use s[start:stop] to get characters from start up to but not including stop:

Python
s = "python" print(s[0:3]) # pyt (indexes 0, 1, 2) print(s[2:5]) # tho (indexes 2, 3, 4)

You can leave either side blank to mean "the beginning" or "the end":

Python
s = "python" print(s[:3]) # pyt (start to index 3) print(s[3:]) # hon (index 3 to the end) print(s[-2:]) # on (last two characters)

The in operator

Use in to check whether one string appears inside another. It returns a boolean (True or False):

Python
s = "python" print("th" in s) # True print("xyz" in s) # False print("PY" in s) # False (case matters!)

This is handy in conditions:

Python
email = "user@example.com" if "@" in email: print("Looks like an email")

Key takeaways

  • Indexing s[i] gets one character; indexes start at 0, and negatives count from the end.
  • Slicing s[start:stop] includes start but excludes stop.
  • Leave a side blank for "beginning" (s[:n]) or "end" (s[n:]).
  • in returns True/False for whether a substring appears — and it's case-sensitive.