How to Split String by Space in Python?


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)

Output

['63', '41', '92', '81', '69', '70']

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.

Output

['63', '41', '92', '81', '69', '70']

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 CodeDescription
09horizontal tab
0ANew line feed
0BVertical Tab
0DCarriage Return/ Form Feed
20Space

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)

Output

['63', '41', '92', '81', '69', '70']

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.