![]() |
VOOZH | about |
String splitting, including spaces refers to breaking a string into parts while keeping spaces as separate elements in the result.
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.
['Hello', ' ', 'World', ' ', 'Python']
Let’s explore some more methods and see how we can split a string including spaces.
Table of Content
This method uses Python’s split() function along with list comprehension to manually handle spaces.
['Hello', 'World', 'Python']
We can manually iterate through the string to split it into words and spaces by using a simple for loop.
['Hello', ' ', 'World', ' ', 'Python']
We can use itertools to split a string and include spaces with some advanced handling.
['Hello', ' ', 'World', ' ', 'Python']