Sub topic 1
Splitting and Joining Strings in Python
Prerequisites
Assume you can run Python code, use variables and lists, call methods, and read return values. You should also know basic for loops and generator expressions.
Strings are immutable: methods return new values
A string is an immutable sequence: its characters cannot be changed in place. String methods therefore return a new string or another value. The original variable stays unchanged unless you assign the result back to it.
text = " Python "
clean = text.strip()
print(text) # Python
print(clean) # PythonThe same rule applies to methods that produce lists. split() does not modify the string. It creates a list of pieces.
flowchart TD
A["original string"] --> B["split method"]
B --> C["new list"]
A --> D["original remains unchanged"]Splitting on a separator with `str.split`
Call split(separator) when a specific character or sequence separates fields.
text = "a,b,,c"
print(text.split(",")) # ['a', 'b', '', 'c']
print("".split(",")) # ['']Every separator is considered. Therefore, consecutive separators create an empty string. An empty input produces a list containing one empty string when an explicit separator is supplied.
Splitting on whitespace with `split()`
With no argument, split() treats each run of whitespace as one separator. It also removes whitespace at the beginning and end.
line = " hello world \n"
print(line.split()) # ['hello', 'world']
print(line.split(" ")) # ['', '', 'hello', '', '', 'world', '\n']These calls have different behavior. split(" ") looks only for the literal space character, so repeated spaces create empty fields. Plain split() also recognizes tabs and line breaks.
Limiting splits with `maxsplit` and `rsplit`
The optional maxsplit argument limits how many separators are used.
print("key=value=more".split("=", 1)) # ['key', 'value=more']
print("a/b/c/d".rsplit("/", 1)) # ['a/b/c', 'd']rsplit() counts from the right. It is useful when the final component has a special meaning, such as a file name or an extension.
Exercise
What does "a b".split(" ") return, and why is it different from "a b".split()?
Show answer
It returns ['a', '', 'b'] because the explicit separator is found twice. The no-argument form treats the two spaces as one whitespace run and returns ['a', 'b'].