0
0
PythonHow-ToBeginner · 3 min read

How to Split String in Python: Simple Guide with Examples

In Python, you can split a string into parts using the split() method. By default, it splits the string at spaces, but you can specify any character as a separator inside the parentheses.
📐

Syntax

The split() method divides a string into a list of smaller strings based on a separator.

  • string.split(separator, maxsplit)
  • separator (optional): The character(s) where the split happens. Defaults to any whitespace.
  • maxsplit (optional): Maximum number of splits to do. The rest of the string remains unsplit.
python
string.split(separator=None, maxsplit=-1)
💻

Example

This example shows how to split a sentence into words using the default space separator, and how to split using a comma.

python
sentence = "Hello world, welcome to Python"

# Split by default whitespace
words = sentence.split()
print(words)

# Split by comma
parts = sentence.split(",")
print(parts)
Output
['Hello', 'world,', 'welcome', 'to', 'Python'] ['Hello world', ' welcome to Python']
⚠️

Common Pitfalls

One common mistake is forgetting that split() returns a list, not a string. Also, if you split by a character not in the string, you get the whole string as one item. Using split() without arguments splits on all whitespace, including tabs and newlines.

python
text = "apple,banana,orange"

# Wrong: expecting a string
result = text.split(",")
print(type(result))  # This prints <class 'list'>

# Right: use the list result
for fruit in result:
    print(fruit)
Output
<class 'list'> apple banana orange
📊

Quick Reference

UsageDescription
string.split()Splits on any whitespace by default
string.split(",")Splits on comma character
string.split("-", 1)Splits on first dash only
string.splitlines()Splits string at line breaks

Key Takeaways

Use split() to break a string into a list by a separator.
By default, split() splits on all whitespace characters.
The method returns a list, so handle the result accordingly.
Specify maxsplit to limit how many splits happen.
If the separator is not found, the result is a list with the original string.