1

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"]
Tomerikoo
  • 18,379
  • 16
  • 47
  • 61
Void S
  • 752
  • 4
  • 14

3 Answers3

2

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']
Tomerikoo
  • 18,379
  • 16
  • 47
  • 61
  • You could add a strip to that `[ss for ss in (s.strip() for sub in name1 for s in sub.split('!')) if ss]` – tdelaney Oct 21 '20 at 19:53
2

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', '']
waykiki
  • 914
  • 2
  • 9
  • 19
  • 3
    It would be a bit more efficient to do `s = "".join(lst)`. – tdelaney Oct 21 '20 at 19:46
  • @tdelaney definitely, thanks for the comment. I shall add this to the code, as the for-loop does look not look like a pythonic solution. – waykiki Oct 21 '20 at 19:47
  • This is not what the op stated as expected output: There is a `''` entry at the end of the list (it's clear why it is there, but it shouldn't)? – Timus Oct 21 '20 at 19:50
  • 1
    @Timus - agreed. There should be a strip and a test for empty in there. – tdelaney Oct 21 '20 at 19:51
  • I assumed the OP made a typo when putting empty spaces around the exclamation marks. The empty strings can be removed in case the OP does not need them (and I suppose he/she doesn't) by simply removing elements from a list. https://stackoverflow.com/questions/1157106/remove-all-occurrences-of-a-value-from-a-list – waykiki Oct 21 '20 at 19:54
  • Sure you can. But if you address both issues (the unwanted whitespace with `strip` and the extra `''` entries with `remove` or otherwise) your solution looks quite different. – Timus Oct 21 '20 at 20:19
0

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

Higs
  • 384
  • 2
  • 7