Python · Module 3 · Lesson 11 min read

Strings & Slicing

Strings are immutable sequences

You can read characters by index, but you can't change them in place. Every string method returns a new string.

Indexing and slicing

  • s[0] is the first character and s[-1] the last.
  • s[start:stop:step], where stop is excluded.
  • s[::-1] reverses a string.

Most-used methods

MethodExample → Result
.upper() / .lower() / .title()"hi".upper() → "HI"
.strip()" hi ".strip() → "hi"
.split(sep)"a,b".split(",") → ["a", "b"]
sep.join(list)"-".join(["a","b"]) → "a-b"
.replace(a, b)"cat".replace("c", "b") → "bat"
.find(x)index of x, or -1
.startswith() / .endswith()True / False
.count(x)how many times x appears
.isdigit() / .isalpha()content checks

Multi-line strings

Triple quotes """...""" keep line breaks.

💡 To build a long string in a loop, collect parts in a list and "".join() them once at the end. It's much faster than +=.

▶️ Runs in the app.

Example

Python
s = "  Hello, World!  "
clean = s.strip()
print(clean.lower())            # hello, world!
print(clean.split(", "))        # ['Hello', 'World!']
print("-".join(["a", "b", "c"]))   # a-b-c

word = "Python"
print(word[0], word[-1])        # P n
print(word[0:3])                # Pyt
print(word[::-1])               # nohtyP

# Is it a palindrome?
text = "Race car"
letters = text.replace(" ", "").lower()
print(letters == letters[::-1]) # True

print("banana".count("a"))      # 3