Python split() Function: Usage and Examples
Hello, this is BlockDMask.
Today, we’ll learn about the split()
function in Python. This function is commonly used to split a string into a list using a specified delimiter.
Let’s explore how it works with some practical examples.
📚 Table of Contents
- What is the
split()
function? - Examples of using
split()
1. What is the split()
function?
Function Syntax:
string.split()
string.split('delimiter')
string.split('delimiter', maxsplit)
string.split(sep='delimiter', maxsplit=n)
The split()
function divides a string into parts based on a separator and returns a list of those parts.
More formally:
string.split(sep, maxsplit)
It splits the string using the specified sep
(separator) up to maxsplit
times and returns a list.
🔸 sep parameter
- Default is
None
, which splits on whitespace and newline characters - Example:
string.split(sep=',')
splits on comma - Short form:
string.split(',')
is also valid
🔸 maxsplit parameter
- Default is
-1
(no limit) string.split(maxsplit=1)
splits only once- Can't use
maxsplit
alone — must follow asep
2. Examples of the split()
Function
🧪 Example 1: Basic split with whitespace
s = "Block DMask Python Flutter CSharp"
print(f'Original string : {s}')
r = s.split()
print(f'After split() : {r}')
Output:
Original string : Block DMask Python Flutter CSharp
After split() : ['Block', 'DMask', 'Python', 'Flutter', 'CSharp']
This splits the string using default whitespace, returning a list of 5 items.
🧪 Example 2: Using a custom separator
s = "11.Block.22.DMask.33.Split.44.Function"
print(f'Original string : {s}')
r0 = s.split()
r1 = s.split('.')
r2 = s.split(sep='.')
print(f's.split() : {r0}')
print(f"s.split('.') : {r1}")
print(f"s.split(sep='.') : {r2}")
Output:
s.split() : ['11.Block.22.DMask.33.Split.44.Function']
s.split('.') : ['11', 'Block', '22', 'DMask', '33', 'Split', '44', 'Function']
s.split(sep='.') : ['11', 'Block', '22', 'DMask', '33', 'Split', '44', 'Function']
This example shows how split()
works with a '.'
separator.
🧪 Example 3: Using maxsplit to limit how many times it splits
s = "alpha.11.beta.22.gamma.33.delta.44"
print(f'Original string : {s}')
r1 = s.split('.', 3)
r2 = s.split(sep='.', maxsplit=3)
r3 = s.split('.', maxsplit=3)
print(f"s.split('.', 3) : {r1}")
print(f"s.split(sep='.', maxsplit=3) : {r2}")
print(f"s.split('.', maxsplit=3) : {r3}")
Output:
s.split('.', 3) : ['alpha', '11', 'beta', '22.gamma.33.delta.44']
s.split(sep='.', maxsplit=3) : ['alpha', '11', 'beta', '22.gamma.33.delta.44']
s.split('.', maxsplit=3) : ['alpha', '11', 'beta', '22.gamma.33.delta.44']
This shows how maxsplit
controls the number of splits.
🧾 Summary
The split()
function is essential for parsing and processing strings in Python.
From basic whitespace splitting to custom delimiters and split limits, it's a tool every Python beginner and pro should master.
Thanks for reading!
— BlockDMask
Comments
Post a Comment