Ojasa Mirai

Ojasa Mirai

Python

Loading...

Learning Level

🟢 Beginner🔵 Advanced
String Basics & CreationString Indexing & SlicingCommon String MethodsString Formatting EssentialsFinding & Replacing TextString Testing & ValidationRegular Expression BasicsText Splitting & JoiningPractical String Projects
Python/String Manipulation/Text Splitting Joining

✂️ Text Splitting & Joining — Break and Rebuild Strings

Learn to split strings into manageable pieces and join them back together efficiently.


🎯 The split() Method

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']

💡 The join() Method

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 line

🎨 splitlines() Method

Split 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

📊 Split & Join Reference

OperationMethodExample
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'`

💡 Practical Example: CSV Processing

# 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")

🎯 URL Building & Parsing

# 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}")

🔑 Real-World Pattern: Parsing Configuration

# 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}")

🔑 Key Takeaways

ConceptRemember
split() creates listReturns list of substrings
join() requires stringWorks only on string delimiters, not lists
Default split() is spaceSplits by any whitespace if no delimiter given
Limit splitsUse second parameter: `split(delimiter, max_splits)`
splitlines() for textBetter than `split("\n")` for robustness

🔗 What's Next?

Now apply all these skills to real-world string projects.


Ready to practice? Challenges | Quiz


Resources

Python Docs

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

Courses

PythonFastapiReactJSCloud

© 2026 Ojasa Mirai. All rights reserved.

TwitterGitHubLinkedIn