Python Split String

Learn how to split a string in Python using str.split(). See examples for splitting by whitespace, comma, newline, multiple spaces, maxsplit, rsplit(), splitlines(), and regex delimiters.

Published

Updated

Read time 5 min read

Reviewed byDeepak Prasad

Python Split String

The split() method breaks a string into a list of smaller strings. By default, it splits on whitespace. You can also pass a separator such as comma, colon, pipe, or newline when your data uses a fixed delimiter.

Tested on: Python 3.13.3; kernel 6.14.0-37-generic.


Quick answer: split a string in Python

Use text.split() to split by whitespace. Use text.split(",") to split by comma. Use text.split(",", maxsplit=1) to split only once.

python
text = "red,green,blue"

print(text.split())
print(text.split(","))
print("name:Deepak:admin".split(":", maxsplit=1))
Output

The first call splits on whitespace in a sentence. The second returns ['red', 'green', 'blue']. The third returns ['name', 'Deepak:admin'] because only the first colon is used.


Python split string quick reference

Task Use
Split by whitespace text.split()
Split by comma text.split(",")
Split by colon text.split(":")
Split by pipe `text.split("
Split by newline text.split("\n")
Split into lines text.splitlines()
Split only once text.split(",", 1)
Split from right text.rsplit(",", 1)
Split by multiple delimiters `re.split(r"[,;
Remove extra spaces after split [x.strip() for x in text.split(",")]
Convert split values to integers [int(x) for x in text.split(",")]
Join split values again separator.join(parts)

Python string split() syntax

Syntax: string.split(sep=None, maxsplit=-1)

  • sep is the separator (delimiter).
  • maxsplit limits the number of splits.
  • split() returns a list.
  • The original string is not changed.

If sep is not given, Python splits on whitespace. When sep is provided, consecutive delimiters can produce empty strings—for example, "1,,2".split(",") returns ['1', '', '2'].


Split string by whitespace

text.split() splits on spaces, tabs, and other whitespace. Consecutive whitespace counts as one separator. Leading and trailing whitespace does not create empty strings at the ends.

python
text = "  This is  Python  Tutorial  "
parts = text.split()

print(parts)
print(type(parts))
Output

You get ['This', 'is', 'Python', 'Tutorial']—a list, not a string.


Split string by comma

Use text.split(",") for CSV-like values, tags, IDs, and simple config strings.

python
colors = "red,green,blue"
ids = "101,102,103"

print(colors.split(","))
print(ids.split(","))
Output

split(",") does not remove spaces automatically. "apple, banana" becomes ['apple', ' banana'].


Split string by comma and remove spaces

Split first, then strip each part when input may include spaces after commas:

python
fruits = "apple, banana, cherry"
clean = [part.strip() for part in fruits.split(",")]

print(clean)
Output

This turns "apple, banana, cherry" into ['apple', 'banana', 'cherry'].


Split string with maxsplit

maxsplit limits how many splits are performed. text.split(",", 1) returns at most two parts.

python
line = "name:Deepak:admin"
pair = "key=value=extra"

print(line.split(":", maxsplit=1))
print(pair.split("=", maxsplit=1))
Output

Useful for key-value strings, headers, and log lines where only the first separator should split.


Split string from the right using rsplit()

rsplit() works like split(), but starts from the right. Use it when you care about the last separator.

python
path = "/home/user/report.csv"
filename = "archive.tar.gz"

print(path.rsplit("/", maxsplit=1))
print(filename.rsplit(".", maxsplit=1))
Output

The path example returns ['/home/user', 'report.csv']. The filename example returns ['archive.tar', 'gz'].


split() vs rsplit()

Method Direction Best for
split() Left to right First fields, normal delimiter splitting
rsplit() Right to left Last field, filename extension, right-side parsing

Split string by newline

text.split("\n") splits only on the newline character. splitlines() is usually better for general line splitting.

python
text = "line one\nline two\nline three\n"

by_split = text.split("\n")
by_lines = text.splitlines()

print(by_split)
print(by_lines)
Output

split("\n") can leave a trailing empty string. splitlines() avoids that extra item after a final newline.


split() vs splitlines()

Task Better method
Split only on "\n" split("\n")
Split text into lines safely splitlines()
Keep line breaks splitlines(keepends=True)
Avoid extra empty item after trailing newline splitlines()
python
text = "a\r\nb\r"

print(text.splitlines())
print(text.splitlines(keepends=True))
Output

Split string by multiple delimiters

str.split() accepts one separator string. For comma, semicolon, or pipe, use re.split():

python
import re

text = "apple,banana;cherry|date"
parts = re.split(r"[,;|]", text)

print(parts)
Output

Keep regex examples short. For complex CSV files, prefer the csv module instead of manual splitting. See Python regex for more pattern-based splitting.


Split string by multiple spaces

Use text.split() for normal whitespace splitting. Avoid text.split(" ") unless you specifically want empty strings from repeated spaces.

python
text = "a  b"

print(text.split())
print(text.split(" "))
Output

split() gives ['a', 'b']. split(" ") can include empty strings between the words.


Split string and convert to numbers

split() returns strings. Convert with int() or float() when you need numbers. A list comprehension keeps the conversion compact:

python
text = "10,20,30"
numbers = [int(x) for x in text.split(",")]

print(numbers)
print(sum(numbers))
Output

Common for comma-separated numeric input from users or config files.


Split string into words

text.split() works for simple whitespace-separated words. It does not remove punctuation automatically.

python
sentence = "Hello, world! Welcome to Python."
words = sentence.split()

print(words)
Output

For punctuation-heavy text, consider regex or dedicated text processing. See Python substring and slicing for related string operations.


Split string into key and value

Use split("=", 1) or split(":", 1) so extra separators stay in the value:

python
config = "host=localhost:8080"
header = "Content-Type: text/html; charset=utf-8"

print(config.split("=", maxsplit=1))
print(header.split(":", maxsplit=1))
Output

maxsplit=1 prevents accidental extra splitting on later delimiters.


Split URL, path, or filename

For simple strings, rsplit() can isolate the last path segment:

python
path = "/var/log/nginx/access.log"
print(path.rsplit("/", maxsplit=1))
Output

For real filesystem paths, use pathlib.Path. For URLs, use urllib.parse. Manual split() is fine for quick examples, not production URL or path logic.


Summary

Use split() to break a string into a list. Call it with no argument to split on whitespace, or pass a separator for delimiter-based splitting. Use maxsplit to limit splits, rsplit() to split from the right, and splitlines() for line-based text. Use re.split() for multiple delimiters or regex patterns. Strip parts or convert types after splitting when your input needs cleanup. Join parts again with separator.join(parts)—the inverse of splitting in Python concatenate strings.


References


Frequently Asked Questions

1. How do you split a string in Python?

Use text.split() to split on whitespace, or text.split(",") to split on a delimiter such as a comma. split() returns a list of strings.

2. What is the difference between split() and splitlines()?

split("\n") splits only on newline characters. splitlines() handles line boundaries more safely and avoids an extra empty item after a trailing newline.

3. What does maxsplit do in Python split()?

maxsplit limits how many splits occur. text.split(",", 1) splits at most once and returns at most two parts.

4. What is the difference between split() and rsplit()?

split() works left to right. rsplit() works right to left, which helps when you only care about the last separator.

5. Can split() use multiple delimiters at once?

No. str.split() accepts one separator string. Use re.split() when you need comma, semicolon, or pipe as delimiters.

6. Does split() change the original string?

No. Strings are immutable. split() returns a new list and leaves the original string unchanged.
Deepak Prasad

R&D Engineer

Founder of GoLinuxCloud with more than 15 years of expertise in Linux, Python, Go, Laravel, DevOps, Kubernetes, Git, Shell scripting, OpenShift, AWS, Networking, and Security. With extensive …