Void S
Void S

Reputation: 802

How to split a list of strings?

Is there a way to split a list of strings per character?

Here is a simple list that I want split per "!":

name1 = ['hello! i like apples!', ' my name is ! alfred!']
first = name1.split("!")
print(first)

I know it's not expected to run, I essentially want a new list of strings whose strings are now separated by "!". So output can be:

["hello", "i like apples", "my name is", "alfred"]

Upvotes: 1

Views: 3878

Answers (3)

Tomerikoo
Tomerikoo

Reputation: 19395

Just loop on each string and flatten its split result to a new list:

name1=['hello! i like apples!',' my name is ! alfred!']
print([s.strip() for sub in name1 for s in sub.split('!') if s])

Gives:

['hello', 'i like apples', 'my name is', 'alfred']

Upvotes: 2

waykiki
waykiki

Reputation: 1094

Based on your given output, I've "solved" the problem. So basically what I do is:

1.) Create one big string by simply concatenating all of the strings contained in your list.

2.) Split the big string by character "!"

Code:

lst = ['hello! i like apples!', 'my name is ! alfred!']
s = "".join(lst)

result = s.split('!')
print(result)

Output:

['hello', ' i like apples', 'my name is ', ' alfred', '']

Upvotes: 2

Higs
Higs

Reputation: 404

Try this:

name1 = ['hello! i like apples!', 'my name is ! alfred!']           
new_list = []                                                       
for l in range(0, len(name1)):                                      
    new_list += name1[l].split('!')
    new_list.remove('')                        
print(new_list)                                                      

Prints:

['hello', ' i like apples', 'my name is ', ' alfred']

Upvotes: 0

Related Questions