Split String of list on K character in Python (original) (raw)

Last Updated : 05 Dec, 2024

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 s**plit() method.

Python `

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:

Using List Comprehension

List comprehension is a more concise and Pythonic way to perform the above method.

Python `

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:

Similar Reads