
Python
Learn to split strings into manageable pieces and join them back together efficiently.
Convert a single string into a list of substrings:
# Split by whitespace (default)
sentence = "Hello world from Python"
words = sentence.split()
print(words) # ['Hello', 'world', 'from', 'Python']
# Split by specific delimiter
csv = "apple,banana,orange,grape"
fruits = csv.split(",")
print(fruits) # ['apple', 'banana', 'orange', 'grape']
# Limit splits
text = "one-two-three-four"
result = text.split("-", 2) # Split into max 3 parts
print(result) # ['one', 'two', 'three-four']Combine list elements into a single string:
# Join with space
words = ["Hello", "beautiful", "world"]
sentence = " ".join(words)
print(sentence) # Hello beautiful world
# Join with comma
items = ["apple", "banana", "orange"]
csv = ",".join(items)
print(csv) # apple,banana,orange
# Join with empty string
chars = ["P", "y", "t", "h", "o", "n"]
word = "".join(chars)
print(word) # Python
# Join with newline (multi-line output)
lines = ["First line", "Second line", "Third line"]
text = "\n".join(lines)
print(text)
# First line
# Second line
# Third lineSplit by line breaks:
text = """First line
Second line
Third line"""
lines = text.splitlines()
print(lines) # ['First line', 'Second line', 'Third line']
# Alternative: split by \n
lines = text.split("\n")
print(lines) # Same result| Operation | Method | Example |
|---|---|---|
| Split by space | `str.split()` | `"a b c".split()` → `['a', 'b', 'c']` |
| Split by delimiter | `str.split(",")` | `"a,b,c".split(",")` → `['a', 'b', 'c']` |
| Split into lines | `str.splitlines()` | Multi-line text → list of lines |
| Join with delimiter | `",".join(list)` | `",".join(['a','b'])` → `'a,b'` |
| Join with nothing | `"".join(list)` | `"".join(['a','b'])` → `'ab'` |
# Parse CSV line
csv_line = "John,30,Engineer,New York"
fields = csv_line.split(",")
name, age, job, city = fields
print(f"{name} is a {job}") # John is a Engineer
# Build CSV line
data = ["Alice", "28", "Designer", "Boston"]
csv_line = ",".join(data)
print(csv_line) # Alice,28,Designer,Boston
# Process multiple lines
csv_data = """Name,Age,City
John,30,NYC
Jane,28,LA
Bob,35,Chicago"""
for line in csv_data.splitlines()[1:]: # Skip header
name, age, city = line.split(",")
print(f"{name} is {age} years old")# Build URL path
path_parts = ["api", "v1", "users", "123"]
url_path = "/" + "/".join(path_parts)
print(url_path) # /api/v1/users/123
# Parse URL
url = "https://example.com/api/v1/users/123"
parts = url.split("/")
print(parts) # ['https:', '', 'example.com', 'api', 'v1', 'users', '123']
# Extract specific parts
domain = parts[2]
endpoint = parts[3]
print(f"Domain: {domain}, Endpoint: {endpoint}")# Parse config line
config_line = "database.host=localhost:5432"
key, value = config_line.split("=", 1) # Split only on first =
print(f"Key: {key}, Value: {value}")
# Key: database.host, Value: localhost:5432
# Parse database URL
url = "user:password@localhost:5432"
credentials, location = url.split("@")
user, password = credentials.split(":")
host, port = location.split(":")
print(f"User: {user}, Host: {host}, Port: {port}")| Concept | Remember |
|---|---|
| split() creates list | Returns list of substrings |
| join() requires string | Works only on string delimiters, not lists |
| Default split() is space | Splits by any whitespace if no delimiter given |
| Limit splits | Use second parameter: `split(delimiter, max_splits)` |
| splitlines() for text | Better than `split("\n")` for robustness |
Now apply all these skills to real-world string projects.
Ready to practice? Challenges | Quiz
Resources
Ojasa Mirai
Master AI-powered development skills through structured learning, real projects, and verified credentials. Whether you're upskilling your team or launching your career, we deliver the skills companies actually need.
Learn Deep • Build Real • Verify Skills • Launch Forward