Python Fundamentals
Strings & String Methods
name = "O'Reilly" # use double quotes when text has an apostrophe
Jr Codex Python Notes
Level: Beginner Prerequisites: Chapter 3 Time to complete: ~25 minutes
Table of Contents
- Creating Strings
- Strings Are Immutable
- Indexing & Slicing
- Common String Methods
- Searching & Checking Content
- Splitting & Joining
- Escape Characters
- Summary & Next Steps
1. Creating Strings
single = 'hello'
double = "hello"
triple = """This can
span multiple
lines"""
name = "O'Reilly" # use double quotes when text has an apostrophe
quote = 'She said "hi"' # use single quotes when text has double quotesSingle and double quotes are functionally identical in Python — choose whichever avoids escaping.
2. Strings Are Immutable
Once created, a string's characters cannot be changed in place. Any "modification" creates a brand-new string object.
name = "Alice"
name[0] = "J" # TypeError: 'str' object does not support item assignment
name = "J" + name[1:] # ✓ this works — builds a NEW string
print(name) # "Jlice"Immutability in Action
──────────────────────────────────────
name = "Alice" name ──→ "Alice" (object #1)
name = "Bob" name ──→ "Bob" (object #2, new object)
"Alice" (object #1, now unreferenced, garbage collected)
──────────────────────────────────────
This matters for performance: repeatedly concatenating strings in a loop creates many throwaway objects (see the pitfall in Chapter 6 on += with lists vs strings).
3. Indexing & Slicing
Strings are sequences — each character has a position (index), starting at 0.
s = "Python"
# P y t h o n
# 0 1 2 3 4 5
# -6 -5 -4 -3 -2 -1
print(s[0]) # 'P' — first character
print(s[-1]) # 'n' — last character (negative indexing)
print(s[2]) # 't'Slicing: s[start:stop:step]
s = "Python"
print(s[0:2]) # 'Py' — index 0 up to (not including) 2
print(s[2:]) # 'thon' — from index 2 to the end
print(s[:4]) # 'Pyth' — from start up to index 4
print(s[::2]) # 'Pto' — every 2nd character
print(s[::-1]) # 'nohtyP' — reversed string| Slice | Meaning |
|---|---|
s[a:b] | Characters from index a to b-1 |
s[:b] | From start to b-1 |
s[a:] | From a to the end |
s[::-1] | The entire string, reversed |
s[::n] | Every n-th character |
4. Common String Methods
Strings come with dozens of built-in methods. These are the ones you'll use daily:
s = " Hello, World! "
print(s.strip()) # "Hello, World!" — removes leading/trailing whitespace
print(s.lower()) # " hello, world! "
print(s.upper()) # " HELLO, WORLD! "
print(s.strip().replace("World", "Python")) # "Hello, Python!"
print(s.strip().title()) # "Hello, World!" — capitalizes each word
print(len(s)) # 17 — length, including whitespace| Method | Purpose | Example → Result |
|---|---|---|
.strip() | Remove leading/trailing whitespace | " hi ".strip() → "hi" |
.lower() / .upper() | Change case | "Hi".upper() → "HI" |
.title() | Capitalize each word | "hello world".title() → "Hello World" |
.replace(old, new) | Replace substring | "cat".replace("c","b") → "bat" |
.startswith(s) / .endswith(s) | Prefix/suffix check | "file.py".endswith(".py") → True |
5. Searching & Checking Content
s = "hello world"
print("world" in s) # True — membership check
print(s.find("world")) # 6 — index where found, -1 if not found
print(s.count("o")) # 2 — occurrences of "o"
print(s.isalpha()) # False — contains a space
print("hello".isalpha()) # True — all alphabetic
print("123".isdigit()) # True — all digits
print("hello123".isalnum()) # True — letters and/or digits only| Check Method | Returns True If... |
|---|---|
.isalpha() | All characters are letters |
.isdigit() | All characters are digits |
.isalnum() | All characters are letters or digits |
.isspace() | All characters are whitespace |
.islower() / .isupper() | All cased characters match that case |
find() vs indexing: .find() returns -1 when not found (no crash), while using .index() raises a ValueError — pick based on whether "not found" is an expected case.
6. Splitting & Joining
Two of the most-used string operations in real code — parsing input and building output.
# Splitting a string into a list
csv_line = "Alice,25,Engineer"
fields = csv_line.split(",")
print(fields) # ['Alice', '25', 'Engineer']
sentence = "the quick brown fox"
words = sentence.split() # splits on any whitespace by default
print(words) # ['the', 'quick', 'brown', 'fox']
# Joining a list into a string
names = ["Alice", "Bob", "Charlie"]
result = ", ".join(names)
print(result) # "Alice, Bob, Charlie"split() and join() are inverses of each other:
─────────────────────────────────────────────
"a,b,c".split(",") → ['a', 'b', 'c']
",".join(['a','b','c']) → "a,b,c"
─────────────────────────────────────────────
7. Escape Characters
Special characters inside strings are written with a backslash:
print("Line one\nLine two") # \n — newline
print("Name:\tAlice") # \t — tab
print("She said \"hi\"") # \" — literal double quote
print("C:\\Users\\Alice") # \\ — literal backslash
print(r"C:\Users\Alice") # raw string — treats \ literally, no escaping needed| Escape | Meaning |
|---|---|
\n | Newline |
\t | Tab |
\\ | Literal backslash |
\" / \' | Literal quote |
r"..." | Raw string — ignores all escapes (great for file paths, regex) |
8. Summary & Next Steps
Key Takeaways
- Strings are immutable sequences — every "modification" method returns a new string.
- Indexing/slicing (
s[start:stop:step]) works identically across all Python sequences (you'll see the same pattern in lists, Chapter 6). .split()and.join()are inverse operations, essential for parsing and building text.- Use raw strings (
r"...") for file paths and regex patterns to avoid escape-character headaches.
Concept Check
- Why does
name[0] = "J"raise aTypeError? - What does
s[::-1]do, and why does it work? - What's the difference between
.find()and.index()when the substring isn't present?
Next Chapter
→ Chapter 5: String Formatting
Jr Codex — 1-on-1 Personalized Coaching | Back to Module Index