Change language

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’] 

Python | String Split including spaces Python functions: Questions

Python | String Split including spaces split: Questions

Shop

Best laptop for Fortnite

$

Best laptop for Excel

$

Best laptop for Solidworks

$

Best laptop for Roblox

$

Best computer for crypto mining

$

Best laptop for Sims 4

$

Best laptop for Zoom

$499

Best laptop for Minecraft

$590

Latest questions

NUMPYNUMPY

psycopg2: insert multiple rows with one query

12 answers

NUMPYNUMPY

How to convert Nonetype to int or string?

12 answers

NUMPYNUMPY

How to specify multiple return types using type-hints

12 answers

NUMPYNUMPY

Javascript Error: IPython is not defined in JupyterLab

12 answers

News

Wiki

Python OpenCV | cv2.putText () method

numpy.arctan2 () in Python

Python | os.path.realpath () method

Python OpenCV | cv2.circle () method

Python OpenCV cv2.cvtColor () method

Python - Move item to the end of the list

time.perf_counter () function in Python

Check if one list is a subset of another in Python

Python os.path.join () method