Python - String Split including spaces
Last Updated :
11 Jan, 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:
- \s+ pattern matches one or more spaces.
- By wrapping \s+ in parentheses, we ensure spaces are captured as separate elements.
- This method is efficient and works well for strings with varying amounts of whitespace.
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:
- split() function splits the string by spaces.
- List comprehension ensures spaces are included in the final result.
- This method is simple but less direct than using regular expressions.
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:
- This method uses a for loop to separate words and spaces.
- Spaces are appended to the result list as separate elements.
- While longer, this method gives us precise control over how the string is split.
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:
- chain.from_iterable() function combines words and spaces into a single list.
- This method is more advanced and less intuitive but can be useful in certain cases.
Similar Reads
Python - Selectively Split in Strings Sometimes, while working with Python strings, we may have to perform a split. Not sometimes, normal one, depending on deliminator but something depending upon programming constructs like elements, numbers, words etc and segregate them. Lets discuss a way in which this task can be solved. Method : Us
3 min read
Python - Avoid Spaces in string length When working with strings in Python, we may sometimes need to calculate the length of a string excluding spaces. The presence of spaces can skew the length when we're only interested in the number of non-space characters. Let's explore different methods to find the length of a string while ignoring
3 min read
Python | Exceptional Split in String Sometimes, while working with Strings, we may need to perform the split operation. The straightforward split is easy. But sometimes, we may have a problem in which we need to perform split on certain characters but have exceptions. This discusses split on comma, with the exception that comma should
4 min read
Split and join a string in Python The goal here is to split a string into smaller parts based on a delimiter and then join those parts back together with a different delimiter. For example, given the string "Hello, how are you?", you might want to split it by spaces to get a list of individual words and then join them back together
3 min read
Python - Check for spaces in string Sometimes, while working with strings in Python, we need to determine if a string contains any spaces. This is a simple problem where we need to check for the presence of space characters within the string. Let's discuss different methods to solve this problem.Using 'in' operator'in' operator is one
3 min read