- Python String split() Method
- Definition and Usage
- Syntax
- Parameter Values
- More Examples
- Example
- Example
- Example
- COLOR PICKER
- Report Error
- Thank You For Helping Us!
- Python Split String by Space
- Examples
- 1. Split given string by single space
- 2. Split given string by one or more adjacent spaces
- 3. Split given string by any whitespace character
- Summary
- Python split string by space [With Examples]
- What is a String?
- Splitting a String
- Limiting Python Splits
- Handling Multiple Python Spaces
- Using Python Regular Expressions for Splitting
- Conclusion
- Python – Split String by Space
- How to split a string in Python?
- Split string by Space
- Fix the number of splits
- Author
Python String split() Method
Split a string into a list where each word is a list item:
txt = «welcome to the jungle»
Definition and Usage
The split() method splits a string into a list.
You can specify the separator, default separator is any whitespace.
Note: When maxsplit is specified, the list will contain the specified number of elements plus one.
Syntax
Parameter Values
Parameter | Description |
---|---|
separator | Optional. Specifies the separator to use when splitting the string. By default any whitespace is a separator |
maxsplit | Optional. Specifies how many splits to do. Default value is -1, which is «all occurrences» |
More Examples
Example
Split the string, using comma, followed by a space, as a separator:
txt = «hello, my name is Peter, I am 26 years old»
Example
Use a hash character as a separator:
Example
Split the string into a list with max 2 items:
# setting the maxsplit parameter to 1, will return a list with 2 elements!
x = txt.split(«#», 1)
COLOR PICKER
Report Error
If you want to report an error, or if you want to make a suggestion, do not hesitate to send us an e-mail:
Thank You For Helping Us!
Your message has been sent to W3Schools.
Top Tutorials
Top References
Top Examples
Get Certified
W3Schools is optimized for learning and training. Examples might be simplified to improve reading and learning. Tutorials, references, and examples are constantly reviewed to avoid errors, but we cannot warrant full correctness of all content. While using W3Schools, you agree to have read and accepted our terms of use, cookie and privacy policy.
Python Split String by Space
You can split a string with space as delimiter in Python using String.split() method.
In this tutorial, we will learn how to split a string by a space character, and whitespace characters in general, in Python using String.split() and re.split() methods.
Refer Python Split String to know the syntax and basic usage of String.split() method.
Examples
1. Split given string by single space
In this example, we will take a string which contains words/items/chunks separated by space character. We shall then split the string by space using String.split() method. split() method returns list of chunks.
Python Program
str = '63 41 92 81 69 70' #split string by single space chunks = str.split(' ') print(chunks)
2. Split given string by one or more adjacent spaces
In this example, we will take a string with chunks separated by one or more single space characters. Then we shall split the string using re.split() function. re.split() returns chunks in a list.
We shall use re python package in the following program. re.split(regular_expression, string) returns list of chunks split from string based on the regular_expression.
Python Program
import re str = '63 41 92 81 69 70' #split string by single space chunks = re.split(' +', str) print(chunks)
Regular Expression + represents one or more immediately occuring spaces. So, one or more single space characters is considered as a delimiter.
One ore more adjacent spaces are considered as a single delimiter because of the regular expression.
3. Split given string by any whitespace character
In this example, we shall split the string into chunks with any white space character as delimiter.
Following are the list of white space characters from ASCII Table.
ASCII Hex Code | Description |
09 | horizontal tab |
0A | New line feed |
0B | Vertical Tab |
0D | Carriage Return/ Form Feed |
20 | Space |
By default, String.split(), with no argument passed, splits the string into chunks with all the white space characters as delimiters.
Python Program
import re str = '63 41\t92\n81\r69 70' #split string by single space chunks = str.split() print(chunks)
Summary
In this tutorial of Python Examples, we learned how to split a string by space using String.split() and re.split() methods. Also, we learned how to split a string by considering all whitespace characters as delimiter.
Python split string by space [With Examples]
In this Python tutorial, we will learn how to split the string by space in Python. In addition, we will explore the various ways of splitting a string by space in Python.
What is a String?
Before delving into the ways of splitting strings in Python, it’s important to understand what a string is.
In Python, a string is a sequence of characters enclosed in single quotes, double quotes, or triple quotes. They are immutable sequences, meaning that once a string is created, its content cannot be changed.
Splitting a String
Python’s built-in split() function is the most common method used to split a string. By default, this function splits a Python string into a list where each word is a list item.
Here is the syntax for the split() function:
str.split(separator, maxsplit)
- separator is the delimiter where the string is split. If not provided, white space is the default separator.
- maxsplit is an optional argument that specifies how many splits to perform. If not provided or -1, it splits at all occurrences.
Let’s look at some examples:
Example#1 Splitting a U.S. Address
Let’s say we have an address string and we want to split it into components:
address = "1600 Pennsylvania Ave NW, Washington, DC 20500" address.split()
In this example, the split() function divides the Python string at each space character and returns a Python list of address components.
Example#2 Splitting U.S. States from a String
Imagine you have a string of several U.S. states, and you want to split them into individual states:
states = "California Texas Florida New York Illinois" states.split()
Here, the split() function splits the Python string at each space character and returns a list of U.S. states.
Limiting Python Splits
If you want to limit the number of splits, you can specify the maxsplit parameter:
Example#1 NFL Teams
teams = "Kansas City Chiefs San Francisco 49ers New England Patriots" teams.split(' ', 3)
Here, the Python split() function splits the string at the first three spaces, and the rest of the string is returned as the fourth element of the list.
Handling Multiple Python Spaces
The split() function treats consecutive spaces as a single separator:
Example#1 American Novels
novels = "The Great Gatsby To Kill a Mockingbird" novels.split()
In this example, regardless of the number of spaces between the words, the Python split() function treats them as a single separator.
Using Python Regular Expressions for Splitting
The re module’s split() function can handle more complex string splitting requirements. It allows for regular expression pattern matching.
Example#1 U.S. Landmarks
import re landmarks = "Statue of Liberty\tGrand Canyon\nMount Rushmore" re.split('\s+', landmarks)
In this example, \s+ is a Python regular expression that matches any whitespace character (spaces, tabs, line breaks).
Conclusion
Python provides various ways to split strings, including the built-in split() function and the re.split() function for more complex patterns. Understanding these methods is crucial for efficient string manipulation in Python. As we’ve seen, splitting a string by space is straightforward and allows for flexibility in handling different scenarios.
I am Bijay Kumar, a Microsoft MVP in SharePoint. Apart from SharePoint, I started working on Python, Machine learning, and artificial intelligence for the last 5 years. During this time I got expertise in various Python libraries also like Tkinter, Pandas, NumPy, Turtle, Django, Matplotlib, Tensorflow, Scipy, Scikit-Learn, etc… for various clients in the United States, Canada, the United Kingdom, Australia, New Zealand, etc. Check out my profile.
Python – Split String by Space
In this tutorial, we will look at how to split a string into a list of strings on the occurrences of a space character in Python with the help of examples.
How to split a string in Python?
You can use the Python string split() function to split a string (by a delimiter) into a list of strings. To split a string by space in Python, pass the space character » » as a delimiter to the split() function.
📚 Discover Online Data Science Courses & Programs (Enroll for Free)
Introductory ⭐
Intermediate ⭐⭐⭐
🔎 Find Data Science Programs 👨💻 111,889 already enrolled
Disclaimer: Data Science Parichay is reader supported. When you purchase a course through a link on this site, we may earn a small commission at no additional cost to you. Earned commissions help support this website and its team of writers.
The following is the syntax –
# split string s by a space s.split(" ")
It returns a list of strings resulting from splitting the original string on the occurrences of a single space, » » .
Let’s look at some examples.
Split string by Space
Here, we pass a single space character, » » as the delimiter to the string split() function.
# string with spaces s = "Identity theft is not a joke." # split string by a space ls = s.split(" ") print(ls)
['Identity', 'theft', 'is', 'not', 'a', 'joke.']
The resulting list contains words resulting from the split of the original string on occurrences of a space character.
Fix the number of splits
You can also specify the maximum number of splits to be made using the maxsplit parameter. By default, the string split() function makes all the possible splits.
Let’s only split the above string into two parts at the occurrence of a space character, » » starting from the left. To split the string into two parts, the maxsplit should be 1 , because we’re making only one split resulting in two strings.
# string with spaces s = "Identity theft is not a joke." # split string by a space ls = s.split(" ", maxsplit=1) print(ls)
['Identity', 'theft is not a joke.']
You can see that the resulting list has only two strings.
Let’s look at another example.
Let’s split the original string into three parts, here we pass maxsplit=2 .
# string with spaces s = "Identity theft is not a joke." # split string by a space ls = s.split(" ", maxsplit=2) print(ls)
['Identity', 'theft', 'is not a joke.']
The resulting list has only three strings.
You might also be interested in –
Subscribe to our newsletter for more informative guides and tutorials.
We do not spam and you can opt out any time.
Author
Piyush is a data professional passionate about using data to understand things better and make informed decisions. He has experience working as a Data Scientist in the consulting domain and holds an engineering degree from IIT Roorkee. His hobbies include watching cricket, reading, and working on side projects. View all posts
Data Science Parichay is an educational website offering easy-to-understand tutorials on topics in Data Science with the help of clear and fun examples.