Skip to content
geeksforgeeks
  • Courses
    • DSA to Development
    • Get IBM Certification
    • Newly Launched!
      • Master Django Framework
      • Become AWS Certified
    • For Working Professionals
      • Interview 101: DSA & System Design
      • Data Science Training Program
      • JAVA Backend Development (Live)
      • DevOps Engineering (LIVE)
      • Data Structures & Algorithms in Python
    • For Students
      • Placement Preparation Course
      • Data Science (Live)
      • Data Structure & Algorithm-Self Paced (C++/JAVA)
      • Master Competitive Programming (Live)
      • Full Stack Development with React & Node JS (Live)
    • Full Stack Development
    • Data Science Program
    • All Courses
  • Tutorials
    • Data Structures & Algorithms
    • ML & Data Science
    • Interview Corner
    • Programming Languages
    • Web Development
    • CS Subjects
    • DevOps And Linux
    • School Learning
  • Practice
    • Build your AI Agent
    • GfG 160
    • Problem of the Day
    • Practice Coding Problems
    • GfG SDE Sheet
  • Contests
    • Accenture Hackathon (Ending Soon!)
    • GfG Weekly [Rated Contest]
    • Job-A-Thon Hiring Challenge
    • All Contests and Events
  • Python Tutorial
  • Interview Questions
  • Python Quiz
  • Python Glossary
  • Python Projects
  • Practice Python
  • Data Science With Python
  • Python Web Dev
  • DSA with Python
  • Python OOPs
Open In App
Next Article:
Python - Check for spaces in string
Next article icon

Python – String Split including spaces

Last Updated : 11 Jan, 2025
Comments
Improve
Suggest changes
Like Article
Like
Report

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.

Table of Content

  • Using list comprehension with split()
  • Using a loop for custom splitting
  • Using itertools.chain() for advanced splitting

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.

Using itertools.chain() for advanced splitting

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.


Next Article
Python - Check for spaces in string
author
manjeet_04
Improve
Article Tags :
  • Python
  • Python Programs
  • Python list-programs
  • Python string-programs
Practice Tags :
  • python

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 on
    3 min read
  • Python - Reversed Split Strings
    In Python, there are times where we need to split a given string into individual words and reverse the order of these words while preserving the order of characters within each word. For example, given the input string "learn python with gfg", the desired output would be "gfg with python learn". Let
    3 min read
  • Python | Split flatten String List
    Sometimes, while working with Python Strings, we can have problem in which we need to perform the split of strings on a particular deliminator. In this, we might need to flatten this to a single String List. Let's discuss certain ways in which this task can be performed. Method #1 : Using list compr
    7 min read
  • Python - Split String on all punctuations
    Given a String, Split the String on all the punctuations. Input : test_str = 'geeksforgeeks! is-best' Output : ['geeksforgeeks', '!', 'is', '-', 'best'] Explanation : Splits on '!' and '-'. Input : test_str = 'geek-sfo, rgeeks! is-best' Output : ['geek', '-', 'sfo', ', ', 'rgeeks', '!', 'is', '-', '
    3 min read
  • Python | Split by repeating substring
    Sometimes, while working with Python strings, we can have a problem in which we need to perform splitting. This can be of a custom nature. In this, we can have a split in which we need to split by all the repetitions. This can have applications in many domains. Let us discuss certain ways in which t
    5 min read
  • Python - Split String on vowels
    Given a String, perform split on vowels. Example: Input : test_str = 'GFGaBst' Output : ['GFG', 'Bst'] Explanation : a is vowel and split happens on that. Input : test_str = 'GFGaBstuforigeeks' Output : ['GFG', 'Bst', 'f', 'r', 'g', 'ks']Explanation : a, e, o, u, i are vowels and split happens on th
    5 min read
geeksforgeeks-footer-logo
Corporate & Communications Address:
A-143, 7th Floor, Sovereign Corporate Tower, Sector- 136, Noida, Uttar Pradesh (201305)
Registered Address:
K 061, Tower K, Gulshan Vivante Apartment, Sector 137, Noida, Gautam Buddh Nagar, Uttar Pradesh, 201305
GFG App on Play Store GFG App on App Store
Advertise with us
  • Company
  • About Us
  • Legal
  • Privacy Policy
  • In Media
  • Contact Us
  • Advertise with us
  • GFG Corporate Solution
  • Placement Training Program
  • Languages
  • Python
  • Java
  • C++
  • PHP
  • GoLang
  • SQL
  • R Language
  • Android Tutorial
  • Tutorials Archive
  • DSA
  • Data Structures
  • Algorithms
  • DSA for Beginners
  • Basic DSA Problems
  • DSA Roadmap
  • Top 100 DSA Interview Problems
  • DSA Roadmap by Sandeep Jain
  • All Cheat Sheets
  • Data Science & ML
  • Data Science With Python
  • Data Science For Beginner
  • Machine Learning
  • ML Maths
  • Data Visualisation
  • Pandas
  • NumPy
  • NLP
  • Deep Learning
  • Web Technologies
  • HTML
  • CSS
  • JavaScript
  • TypeScript
  • ReactJS
  • NextJS
  • Bootstrap
  • Web Design
  • Python Tutorial
  • Python Programming Examples
  • Python Projects
  • Python Tkinter
  • Python Web Scraping
  • OpenCV Tutorial
  • Python Interview Question
  • Django
  • Computer Science
  • Operating Systems
  • Computer Network
  • Database Management System
  • Software Engineering
  • Digital Logic Design
  • Engineering Maths
  • Software Development
  • Software Testing
  • DevOps
  • Git
  • Linux
  • AWS
  • Docker
  • Kubernetes
  • Azure
  • GCP
  • DevOps Roadmap
  • System Design
  • High Level Design
  • Low Level Design
  • UML Diagrams
  • Interview Guide
  • Design Patterns
  • OOAD
  • System Design Bootcamp
  • Interview Questions
  • Inteview Preparation
  • Competitive Programming
  • Top DS or Algo for CP
  • Company-Wise Recruitment Process
  • Company-Wise Preparation
  • Aptitude Preparation
  • Puzzles
  • School Subjects
  • Mathematics
  • Physics
  • Chemistry
  • Biology
  • Social Science
  • English Grammar
  • Commerce
  • World GK
  • GeeksforGeeks Videos
  • DSA
  • Python
  • Java
  • C++
  • Web Development
  • Data Science
  • CS Subjects
@GeeksforGeeks, Sanchhaya Education Private Limited, All rights reserved
We use cookies to ensure you have the best browsing experience on our website. By using our site, you acknowledge that you have read and understood our Cookie Policy & Privacy Policy
Lightbox
Improvement
Suggest Changes
Help us improve. Share your suggestions to enhance the article. Contribute your expertise and make a difference in the GeeksforGeeks portal.
geeksforgeeks-suggest-icon
Create Improvement
Enhance the article with your expertise. Contribute to the GeeksforGeeks community and help create better learning resources for all.
geeksforgeeks-improvement-icon
Suggest Changes
min 4 words, max Words Limit:1000

Thank You!

Your suggestions are valuable to us.

What kind of Experience do you want to share?

Interview Experiences
Admission Experiences
Career Journeys
Work Experiences
Campus Experiences
Competitive Exam Experiences