📘 Lesson 06 · Beginner

Python Strings

Learn Python string methods, slicing, f-strings, and common operations with full examples and output.

Indexing and Slicing

A string is a sequence of characters, each at a numbered position called an index. Python uses zero-based indexing — the first character is at index 0. Negative indices count from the end: -1 is the last character, -2 is second-to-last. Slicing (s[start:stop]) extracts a portion — start is included, stop is excluded. A third parameter is the step: s[::-1] reverses the string.

index.py
s = "Hello, Python!"
print(len(s))        # 14 characters
print(s[0])         # first char: H
print(s[-1])        # last char: !
print(s[0:5])       # chars 0–4: Hello
print(s[7:])        # from index 7 to end
print(s[::-1])      # reversed
▶ Output
14
H
!
Hello
Python!
!nohtyP ,olleH

Essential String Methods

Strings come with dozens of built-in methods. Call them with dot notation: string.method(). Crucially, strings are immutable — methods never change the original string, they always return a new one. This means you need to store the result if you want to use it.

methods.py
s = "  hello world  "
print(s.strip())        # remove whitespace from both ends
print(s.upper())        # ALL CAPS
print(s.title())        # Title Case Each Word
print(s.replace("hello", "hi"))  # find and replace
print(s.count("l"))    # count occurrences
print(s.find("world")) # index of first match
▶ Output
hello world
  HELLO WORLD  
  Hello World  
  hi world  
3
8

f-Strings — The Best Way to Format

Introduced in Python 3.6, f-strings are the cleanest way to embed variables and expressions inside strings. Prefix the string with f and put any Python expression inside {}. You can apply formatting codes like :.2f for 2 decimal places, :>10 for right-alignment, and more.

fstring.py
name = "Alice"
age = 28
score = 95.678

print(f"Name: {name}, Age: {age}")
print(f"Score: {score:.2f}")       # 2 decimal places
print(f"Double age: {age * 2}")    # expressions work
print(f"Upper: {name.upper()}")    # method calls too
▶ Output
Name: Alice, Age: 28
Score: 95.68
Double age: 56
Upper: ALICE

split() and join()

split(separator) breaks a string into a list of substrings wherever the separator appears. join(list) merges a list back into a single string with a separator between items. These two methods are used constantly when processing text, reading CSV data, or handling user input.

split.py
csv = "apple,banana,cherry"
fruits = csv.split(",")
print(fruits)          # list of 3 strings

joined = " | ".join(fruits)
print(joined)          # back to a string

# Check if a substring exists
print("banana" in csv)   # True
▶ Output
['apple', 'banana', 'cherry']
apple | banana | cherry
True
Use in to check if a substring exists: 'ell' in 'hello' returns True. This is cleaner and faster than searching manually.

🧠 Quick Check

Which method removes leading and trailing whitespace?

clean()
strip()
trim()
remove()

Tags

stringsf-stringslicingstring methodsupperlowerreplacesplitstrip