Python: Strings & Containers Review

Last updated: 2026-09-22

In previous lessons, we covered lists, tuples, dictionaries, sets, and string methods. Now let's combine them — using the most common "combos" to solve real problems. These techniques are used daily in professional programming.


Related Built-in Functions:enumerate() sorted() split() join() str() zip() None

1. split() Working with Lists

split() breaks a string into a list — the first step in data processing:

PYTHON
# CSV data parsing
line = "Alice,25,Beijing,Engineer"
fields = line.split(",")
print(fields)               # ['Alice', '25', 'Beijing', 'Engineer']

# Split by whitespace (default)
text = "hello   world    python"
words = text.split()
print(words)                # ['hello', 'world', 'python']

# Limit the number of splits
data = "2026-06-23-15-30-00"
parts = data.split("-", 3)
print(parts)                # ['2026', '06', '23', '15-30-00']

▶ Example: Parsing a Config File (Difficulty ⭐⭐)

▶ Try it Yourself

Output:

TEXT 📖 Display only
{'host': 'localhost', 'port': '8080', 'debug': 'true', 'theme': 'dark'}
Current host: localhost
Current port: 8080


2. The Power of join()

join() is the reverse of split() — it merges a list into a string:

PYTHON
# Basic usage
words = ["Hello", "World", "Python"]
sentence = " ".join(words)
print(sentence)             # Hello World Python

# Join with commas
csv = ",".join(["Alice", "25", "Beijing"])
print(csv)                  # Alice,25,Beijing

# Join with newlines
lines = "\n".join(["First line", "Second line", "Third line"])
print(lines)

(1) Performance Advantages of join()

PYTHON
# ❌ Not recommended — string concatenation in a loop
result = ""
for i in range(1000):
    result += str(i) + ","
# This creates 1000 temporary string objects (strings are immutable)

# ✅ Recommended — collect in a list + join()
parts = [str(i) for i in range(1000)]
result = ",".join(parts)
# One merge, much more efficient

▶ Example: Formatting a Table (Difficulty ⭐⭐)

▶ Try it Yourself

Output:

TEXT 📖 Display only
Name | Age | City
─────────────────────────
Alice | 25 | Beijing
Bob | 30 | Shanghai
Charlie | 22 | Guangzhou


3. sorted() with Strings and Dictionaries

sorted() works on any iterable, not just lists:

PYTHON
# Sort a string — alphabetical order
text = "python"
sorted_chars = sorted(text)
print(sorted_chars)                 # ['h', 'n', 'o', 'p', 't', 'y']
print("".join(sorted_chars))        # hnopty — recombined

# Sort a dictionary — sorts keys by default
d = {"banana": 3, "apple": 5, "cherry": 2}
sorted_keys = sorted(d)
print(sorted_keys)                  # ['apple', 'banana', 'cherry']

# Sort by value
sorted_by_value = sorted(d.items(), key=lambda x: x[1])
print(sorted_by_value)              # [('cherry', 2), ('banana', 3), ('apple', 5)]

# Sort a set
s = {3, 1, 4, 1, 5, 9}
sorted_set = sorted(s)
print(sorted_set)                   # [1, 3, 4, 5, 9]

▶ Example: Custom Sort Rule (Difficulty ⭐⭐)

▶ Try it Yourself

Output:

TEXT 📖 Display only
# Function defined successfully


4. enumerate() and zip()

These two built-in functions are extremely common in daily work.

(1) enumerate() — Get Index While Iterating

PYTHON
fruits = ["apple", "banana", "orange"]

# Without enumerate — clunky
for i in range(len(fruits)):
    print(f"{i + 1}. {fruits[i]}")

# With enumerate — elegant
for i, fruit in enumerate(fruits, 1):    # start=1 for 1-based counting
    print(f"{i}. {fruit}")

(2) zip() — Parallel Iteration Over Multiple Lists

PYTHON
names = ["Alice", "Bob", "Charlie"]
scores = [85, 92, 78]
cities = ["Beijing", "Shanghai", "Guangzhou"]

# Iterate over three lists simultaneously
for name, score, city in zip(names, scores, cities):
    print(f"{name}: {score} points, from {city}")

Output:

TEXT 📖 Display only
Alice: 85 points, from Beijing
Bob: 92 points, from Shanghai
Charlie: 78 points, from Guangzhou

▶ Example: Student Score Report (Difficulty ⭐⭐⭐)

▶ Try it Yourself

Output:

TEXT 📖 Display only
=== Student Score Report ===


5. Comprehensive Data Processing Case

Let's apply everything we've learned to a real-world scenario:

(1) Case: Log Analysis (Difficulty ⭐⭐⭐)

PYTHON
# Simulated server log
log_data = """
2026-06-20 10:23:45 INFO  User 1001 logged in
2026-06-20 10:25:12 ERROR Database connection timeout
2026-06-20 10:26:30 INFO  User 1002 logged in
2026-06-20 10:27:45 WARN  Disk usage 85%
2026-06-20 10:28:10 ERROR User 1001 request timeout
2026-06-20 10:29:00 INFO  User 1001 logged out
"""

# 1. Split by lines
lines = log_data.strip().split("\n")

# 2. Parse each log entry
parsed = []
for line in lines:
    parts = line.split()
    timestamp = f"{parts[0]} {parts[1]}"
    level = parts[2]
    message = " ".join(parts[3:])
    parsed.append({"time": timestamp, "level": level, "msg": message})

# 3. Count by level
level_count = {}
for entry in parsed:
    level = entry["level"]
    level_count[level] = level_count.get(level, 0) + 1

# 4. Output sorted by level
print("=== Log Statistics ===")
for level, count in sorted(level_count.items()):
    print(f"{level}: {count} entries")

# 5. Filter all ERRORs
print("\n=== Error Details ===")
errors = [e for e in parsed if e["level"] == "ERROR"]
for e in errors:
    print(f"[{e['time']}] {e['msg']}")

Output:

TEXT 📖 Display only
=== Log Statistics ===
ERROR: 2 entries
INFO: 3 entries
WARN: 1 entry

=== Error Details ===
[2026-06-20 10:25:12] Database connection timeout
[2026-06-20 10:28:10] User 1001 request timeout


6. Common Use Cases


Related Built-in Functions:enumerate() sorted() split() join() str() zip() None

❓ FAQ

Q What's the difference between split() and split(" ")?
A split() without arguments splits on any whitespace (spaces, newlines, tabs) and automatically removes empty strings. split(" ") only splits on single spaces; consecutive spaces produce empty strings. In most cases, split() without arguments is the better choice.
Q Does join() require all elements in the list to be strings?
A Yes. ",".join([1, 2, 3]) will error. Convert numbers to strings first: ",".join(str(x) for x in [1, 2, 3]) or use str() in a list comprehension.
Q What happens when zip() processes lists of different lengths?
A zip() stops at the shortest list. If one of three lists has only 2 elements, zip() only produces 2 pairs. To pad with None for the longest list, use itertools.zip_longest().

📖 Summary


📝 Exercises

  1. Basic (Difficulty ⭐): Given s = "apple,banana,orange,grape", use split() to break it into a list, then use join() to output "apple | banana | orange | grape".

  2. Intermediate (Difficulty ⭐⭐): Given two lists students = ["Alice", "Bob", "Charlie"] and scores = [85, 92, 78], use zip() and enumerate() to output a ranked report:

    TEXT 📖 Display only
    #1: Bob — 92 points
    #2: Alice — 85 points
    #3: Charlie — 78 points
    
  3. Challenge (Difficulty ⭐⭐⭐): Write a "Simple CSV Generator." Given a list of lists data = [["Name", "Age", "City"], ["Alice", 25, "Beijing"], ["Bob", 30, "Shanghai"]], output it as a CSV string (comma-separated rows). Hint: Use str() in list comprehension for numbers, ",".join() for each row, "\n".join() for all rows.

Web-Tutorial.com

Web-Tutorial Tech Team

A team of developers maintaining programming tutorials. Each tutorial is written and reviewed by developers with expertise in that field. We work to keep our content accurate and reliable — if you spot an issue, please let us know.

100%

🙏 帮我们做得更好

我们是刚上线的编程教程站,几个人的小团队,精力有限。页面虽经检查,难免还有疏漏——链接失效、排版错乱、内容有误、语言生硬……

如果您发现了,麻烦告诉我们,我们会在收到反馈后第一时间进行修复,再次感谢您的光临 🙏