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"]
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']
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', '']
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']
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.