Python | String Split including spaces



Method # 1: Using split () + list comprehension

This kind of operation can be performed using the list comprehension and split function. The main difference in not skipping spaces is that we deliberately add spaces that we might have missed in the process, after each element.

# Python3 demo code
# String Split including spaces
# using list comprehension + split ()

 
# initialization string

test_string = "GfG is Best"

 
# print original line

print ( "The original string:" + str (test_string))

  
# using a list comprehension + split ()
# String Split including spaces

res = [i for j in test_string.split () for i in (j, `` )] [: - 1 ]

 
# result print

print ( "The list without omitting spaces: " + str (res))

Output:

 The original string: GfG is Best The list without omitting spaces: [`GfG `,` `,` is`, ``, `Best`] 

Method # 2: Using zip () + chain () + cycle ()

This particular task can also be accomplished using a combination of the 3 above functions. The zip function can be used to bind logic, chaining and looping functions to perform the task of inserting a space at the appropriate position.

# Python3 demo code
# String Split including spaces
# using zip () + chain () + cycle ()

from itertools import chain, cycle

 
# initializing string

test_string = "GfG is Best"

 
# print original line

print ( "The original string:" + str (test_string))

 
# using zip () + chain () + cycle ()
# String Split including spaces

res = list (chain ( * zip (test_string.split (), cycle ( `` )))) [: - 1 ]

  
# print result

print ( "The list without omittin g spaces: " + str (res))

Output:

 The original string: GfG is Best The list without omitting spaces: [`GfG`,` `,` is`, ``, `Best`]