All lessons
🔤

Python Strings

Work with text data

Reward
+50 XP

Creating strings

Strings can use single quotes, double quotes, or triple quotes for multi-line.

a = 'Hello'
b = "World"
c = """This is
multi-line"""
print(a, b)
print(c)

String methods

Strings have many useful methods: upper(), lower(), strip(), replace(), split(), find(), count().

s = "  Hello, World!  "
print(s.strip())
print(s.upper())
print(s.replace("World", "Python"))

Slicing

Access parts of a string with [start:end] notation. Indices start at 0.

s = "Hello"
print(s[0])      # H
print(s[1:4])    # ell
print(s[-1])     # o

Try it yourself

Run the example below. Edit it and see what changes.

main.py
Output
Press Run to execute (Ctrl/Cmd+Enter)

Common mistakes

  • Strings are immutable — s[0] = 'h' will error.
  • Off-by-one: s[1:4] includes index 1, 2, 3 but NOT 4.
  • Forgetting len() to get string length.