I've got a function to split a newline separated list of strings into a list, removing any whitespace, None, or empty values.
All strings must be the same length. I check for that. I could raise an exception if they weren't, but I decided instead to return a list consisting of the strings with the most common length instead. That way if there were a few erroneous strings the function would keep chugging.
This is what I did. It works. But I'm curious if there are other betters ways of doing this.
To be clear, for a list of strings, I want a list of strings which are of the most frequent length.
Thank you.
def same_length_string_list(string_list):
same_length = all(len(string_list[0]) == len(item) for item in string_list)
# If the contents of the list aren't all the same length
# Then find out the most common length, and return a list of all items with that length.
if not same_length:
string_lengths = {}
for i in string_list:
if len(i) in string_lengths: # Iterate the length key if it exists
string_lengths[len(i)] = string_lengths[len(i)] + 1
else: #If the length key doesn't exist already make a new one
string_lengths[len(i)] = 1
# Length of the most common word length. Gives the key of the highest value in a dict.
string_length = max(string_lengths, key=string_lengths.get)
string_list = [i for i in string_list if len(i) == string_length]
return string_list```