Split String of list on K character in Python
In this article, we will explore various methods to split string of list on K character in Python. The simplest way to do is by using a loop and split().
Using Loop and split()
In this method, we'll iterate through each word in the list using for loop and split it based on given K character using split() method.
a = ['Gfg is best', 'for Geeks', 'Preparing']
# Character to split on (space)
k = ' '
# Initialize an empty list to store the result
res = []
# Loop through each string in the list
for word in a:
# Split the string at each space 'K'
split_word = word.split(k)
res.append(split_word)
print(res)
Output
[['Gfg', 'is', 'best'], ['for', 'Geeks'], ['Preparing']]
Explanation:
- word.split(K): split() method splits each word at every occurrence of K.
- For word 'Gfg is best', it splits into ['Gfg', 'is', 'best'].
- For the word 'for Geeks', it splits into ['for', 'Geeks'].
Using List Comprehension
List comprehension is a more concise and Pythonic way to perform the above method.
a = ['Gfg is best', 'for Geeks', 'Preparing']
# Character to split on (space)
K = ' '
# Using list comprehension to split
# each string in the list on the space character
res = [word.split(K) for word in a]
print(res)
Output
[['Gfg', 'is', 'best'], ['for', 'Geeks'], ['Preparing']]
Explanation:
- List comprehension iterates over each word in the list a and splits it at every occurrence of K
- split(K) performs the split operation and resulting substrings are collected into a list.