str.split()
Python · Strings
Theory
.split(sep) cuts a string at every occurrence of sep and returns a list of the pieces. 'Asha,IT,95000'.split(',') gives ['Asha', 'IT', '95000']. Notice the pieces are still strings: '95000' must go through int() before you can do maths with it. An optional maxsplit limits the cuts: 'a,b,c'.split(',', 1) gives ['a', 'b,c'].
Calling .split() with no argument is special: it splits on any run of whitespace (spaces, tabs, newlines) and ignores leading and trailing whitespace, so ' a b c'.split() gives ['a', 'b', 'c']. With an explicit separator every occurrence counts, so empty fields appear: 'a,,b'.split(',') gives ['a', '', 'b']. The reverse operation is join, called on the separator: ','.join(['a', 'b']) gives 'a,b'. For real CSV files with quoted commas, use the csv module.
Why we use it
Text often packs several values into one line: CSV rows, full names, log entries, tags. split() turns that line into a list you can index, loop over and convert field by field.
When to use it
Use split(',') for simple delimited lines, split() for words separated by spaces, and maxsplit when only the first separator matters. For CSV data with quotes or embedded commas, use the csv module or pandas.read_csv instead.
How it works
- Call line.split(',')
- Scan the string from left to right
- Reached a comma? Yes: End the current piece and start a new one. No: Add the character to the current piece.
- After the last character, close the final piece
- Return a list of strings: ['Asha', 'IT', '95000']
Syntax
string.split(separator)Example
line = 'Asha,IT,95000'
print(line.split(','))Key points
- Default separator (no argument) splits on any whitespace
- Pieces are strings: convert with int() or float() before maths
- With an explicit separator, empty fields appear: 'a,,b' -> ['a', '', 'b']
- maxsplit limits the number of cuts: split(',', 1)
- ','.join(list) does the reverse: joins a list back into a string