Python – Split String of list on K character

Sometimes while working with data, we can have a problem in which we need to perform split operation on Strings, and sometimes, we might also require to perform them into nested strings overall. Lets discuss certain ways in which this task can be performed.

Method #1 : Using loop + split()
The combination of above functionalities can be used to perform this task. In this, we iterate through each list string and perform a manual split and then add the new elements to that list using extend() using loop.

filter_none

edit
close

play_arrow

link
brightness_4
code

# Python3 code to demonstrate 
# Split String of list on K character
# using loop + split()
  
# Initializing list 
test_list = ['Gfg is best', 'for Geeks', 'Preparing']
  
# printing original list
print("The original list is : " + str(test_list))
  
K = ' '
  
# Split String of list on K character
# using loop + split()
res = []
for ele in test_list:
    sub = ele.split(K)
    res.extend(sub)
  
# printing result 
print ("The extended list after split strings : " + str(res))

chevron_right


Output :

The original list is : ['Gfg is best', 'for Geeks', 'Preparing']
The extended list after split strings : ['Gfg', 'is', 'best', 'for', 'Geeks', 'Preparing']

 

Method #2 : Using join() + split()
The combination of above functions can be used to perform this task. In this, we join split all the elements of list and then join each of them to make it split by K.

filter_none

edit
close

play_arrow

link
brightness_4
code

# Python3 code to demonstrate 
# Split String of list on K character
# using join() + split()
  
# Initializing list 
test_list = ['Gfg is best', 'for Geeks', 'Preparing']
  
# printing original list
print("The original list is : " + str(test_list))
  
K = ' '
  
# Split String of list on K character
# using join() + split()
res = K.join(test_list).split(K)
  
# printing result 
print ("The extended list after split strings : " + str(res))

chevron_right


Output :

The original list is : ['Gfg is best', 'for Geeks', 'Preparing']
The extended list after split strings : ['Gfg', 'is', 'best', 'for', 'Geeks', 'Preparing']



My Personal Notes arrow_drop_up

Check out this Author's contributed articles.

If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to contribute@geeksforgeeks.org. See your article appearing on the GeeksforGeeks main page and help other Geeks.

Please Improve this article if you find anything incorrect by clicking on the "Improve Article" button below.


Article Tags :

Be the First to upvote.


Please write to us at contribute@geeksforgeeks.org to report any issue with the above content.