How to Split a String (and Join It Back) Without the Usual Surprises
Split strings by a delimiter or whitespace in Python, JavaScript, Java, C# and Go, and avoid the empty-string, regex-dot, limit and CSV traps that make split return the wrong pieces.
By Software Side Hustles Editorial Team · Published · Updated · 4 min read
Quick answer: Python s.split(","), JavaScript s.split(","), Java s.split(","), C# s.Split(','), Go strings.Split(s, ","). To split on any run of whitespace use Python s.split(), JavaScript s.trim().split(/\s+/), Java s.trim().split("\\s+") or Go strings.Fields(s). And if the text is CSV, use a CSV parser instead of split.
Split behaviour compared
| Input | Python split(",") | JavaScript split(",") | Java split(",") |
|---|---|---|---|
"a,b,,c" | ['a', 'b', '', 'c'] | ["a", "b", "", "c"] | [a, b, , c] |
"a,b,," | ['a', 'b', '', ''] | ["a", "b", "", ""] | [a, b] — trailing empties removed |
"" | [''] | [""] | [""] |
"a.b" split on "." | ['a', 'b'] | ["a", "b"] | [] — . is a regex! |
That last column explains a lot of confused Stack Overflow searches.
How do I split a string in Python?
"a,b,c".split(",") # ['a', 'b', 'c']"key=value=x".split("=", 1) # ['key', 'value=x'] — split at most once"path/to/file.txt".rsplit("/", 1) # ['path/to', 'file.txt']"key=value".partition("=") # ('key', '=', 'value')"line1\nline2\r\n".splitlines() # ['line1', 'line2']The most important distinction in Python is split() versus split(" "):
" a b ".split() # ['a', 'b'] — any whitespace, runs collapsed, ends trimmed" a b ".split(" ") # ['', '', 'a', '', 'b', ''] — every single space is a separator"".split() # []"".split(",") # ['']With no argument, split() is almost always what you want for words. With an explicit separator, empty fields are kept — which is correct for structured data, where an empty field means something.
How do I split a string in JavaScript?
"a,b,c".split(","); // ["a", "b", "c"]" a b ".trim().split(/\s+/); // ["a", "b"]"a1b22c".split(/\d+/); // ["a", "b", "c"]"abc".split(""); // ["a", "b", "c"] — but see the emoji warning belowThe limit argument does not do what Python's maxsplit does — it discards the remainder:
"a,b,c".split(",", 2); // ["a", "b"] — "c" is goneTo split only on the first separator, use indexOf:
const i = s.indexOf("=");const [key, value] = i === -1 ? [s, ""] : [s.slice(0, i), s.slice(i + 1)];Splitting with "" breaks emoji into invalid halves; use [...s] or Intl.Segmenter instead. See how to reverse a string for details.
How do I split a string in Java?
String.split takes a regular expression, and that causes most Java split bugs:
"a.b.c".split("."); // [] — "." matches every character"a.b.c".split("\\."); // [a, b, c]"a|b".split("|"); // [a, |, b] — empty regex alternation"a|b".split(Pattern.quote("|")); // [a, b]Java also removes trailing empty strings unless you pass a negative limit:
"a,b,,".split(","); // [a, b]"a,b,,".split(",", -1); // [a, b, , ]When parsing fixed-width records, that difference silently changes the number of columns. Use -1 whenever every field matters.
How do I split a string in C# and Go?
"a, b,,c".Split(',', StringSplitOptions.RemoveEmptyEntries | StringSplitOptions.TrimEntries);// ["a", "b", "c"]C#'s Split takes plain characters or strings, not regexes; use Regex.Split when you need patterns.
strings.Split("a,b,c", ",") // [a b c]strings.Fields(" a b ") // [a b]strings.SplitN("k=v=x", "=", 2) // [k v=x]len(strings.Split("", ",")) // 1 — a slice containing one empty stringHow do I join a list back into a string?
| Language | Join |
|---|---|
| Python | ", ".join(items) — items must be strings: ", ".join(map(str, numbers)) |
| JavaScript | items.join(", ") |
| Java | String.join(", ", items) or stream.collect(Collectors.joining(", ")) |
| C# | string.Join(", ", items) |
| Go | strings.Join(items, ", ") |
Python's join is a method on the separator, and it raises TypeError: sequence item 0: expected str instance, int found if you pass numbers. Convert them first.
Why you should not split CSV on commas
'Smith,"London, UK",42'.split(",")# ['Smith', '"London', ' UK"', '42'] — wrongCSV allows quoted fields containing commas, escaped quotes and even newlines. Use a real parser:
import csv, ionext(csv.reader(io.StringIO('Smith,"London, UK",42')))# ['Smith', 'London, UK', '42']In JavaScript use a library such as Papa Parse; in Java, Apache Commons CSV or OpenCSV. The same applies to query strings (URLSearchParams, urllib.parse.parse_qs), file paths (pathlib, path.join) and anything with an established format — the hand-rolled split works until the first value that contains the separator.
Frequently asked questions
How do I split a string into characters?
Python: list(s). JavaScript: [...s]. Java: s.toCharArray() or s.codePoints() for full Unicode. Go: []rune(s).
How do I split on multiple delimiters?
Use a regex: re.split(r"[;,\s]+", s) in Python, s.split(/[;,\s]+/) in JavaScript, s.split("[;,\\s]+") in Java.
How do I split a string into lines?
Python s.splitlines(), JavaScript s.split(/\r?\n/), Java s.lines() (Java 11+). These handle Windows \r\n line endings, which a plain split("\n") leaves as a trailing \r on every line. See reading a file line by line.
How do I split a string every N characters?
Python: [s[i:i + n] for i in range(0, len(s), n)]. JavaScript: s.match(/.{1,3}/gs) for chunks of three (build the pattern with new RegExp for a variable size).
Where this skill pays off
Knowing that Java's split(".") returns an empty array, or that CSV cannot be split on commas, is exactly the kind of judgement AI code-review work relies on. If you enjoy catching these details, see how to prepare for technical AI evaluation work.