A RetroSearch Logo

Home - News ( United States | United Kingdom | Italy | Germany ) - Football scores

Search Query:

Showing content from https://www.geeksforgeeks.org/python-string-split-including-spaces/ below:

Python - String Split including spaces

Python - String Split including spaces

Last Updated : 11 Jul, 2025

String splitting, including spaces refers to breaking a string into parts while keeping spaces as separate elements in the result.

Using regular expressions (Most Efficient)

re.split() function allows us to split a string based on a custom pattern. We can use it to split the string while capturing the spaces as separate elements.

Python
import re

s = "Hello World Python"
# Split the string including spaces
res = re.split(r"(\s+)", s)
print(res)  

Output
['Hello', ' ', 'World', ' ', 'Python']
Explanation:

Let’s explore some more methods and see how we can split a string including spaces.

Using list comprehension with split()

This method uses Python’s split() function along with list comprehension to manually handle spaces.

Python
s = "Hello World Python"
# Split the string and add spaces back as separate elements
res = [part if part.strip() else " " for part in s.split(" ")]
print(res)  

Output
['Hello', 'World', 'Python']
Explanation: Using for loop for custom splitting

We can manually iterate through the string to split it into words and spaces by using a simple for loop.

Python
s = "Hello World Python" 
a = []  # List to store the result
temp = ""  # Temporary variable to accumulate characters

for c in s:  
    if c != " ":  # If the character is not a space
        temp += c  # Add character to current word
    else:  
        a.append(temp)  # Add word to result
        a.append(c)  # Add space as a separate element
        temp = ""  # Reset temp for next word

if temp:  # Add the last word if exists
    a.append(temp)

print(a)  

Output
['Hello', ' ', 'World', ' ', 'Python']
Explanation:

We can use itertools to split a string and include spaces with some advanced handling.

Python
from itertools import chain

s = "Hello World Python"
res = list(chain.from_iterable((word, " ") for word in s.split(" ")))
if res[-1] == " ":
    res.pop()  # Remove trailing space
print(res) 

Output
['Hello', ' ', 'World', ' ', 'Python']
Explanation:

RetroSearch is an open source project built by @garambo | Open a GitHub Issue

Search and Browse the WWW like it's 1997 | Search results from DuckDuckGo

HTML: 3.2 | Encoding: UTF-8 | Version: 0.7.4