Here’s a Python function to split words using a separator and remove empty results:
class Solution(object):
def splitWordsBySeparator(self, words, separator):
ans = []
for i in range(len(words)): # Loop through each word inthe list
ans.append(words[i].split(separator)) # Split wordby the separator
new = sum(ans, []) # Flatten the list (converts list oflists into a single list)
res = list(filter(None, new)) # Remove empty stringsfrom the list
return res # Return the cleaned list of words
How It Works
- It takes two inputs:
words: A list of strings.
separator: A character used to split the words.
It loops through each word and splits it using the separator.
The split words are stored in a list (ans), which may contain sublists.
It flattens ans using sum(ans, []) to merge all sublists into a single list.
It removes empty strings using filter(None, new) to get rid of unnecessary empty elements.
Finally, it returns the cleaned list of words.
Example
solution = Solution()
words = ["hello.world", "python.is.awesome", "split,this"]
separator = "."
result = solution.splitWordsBySeparator(words, separator)
print(result)
Output
['hello', 'world', 'python', 'is', 'awesome', 'split', 'this']
Top comments (0)