有幾種方法可以去除字符串中的空字符串:
def remove_empty_strings(strings):
result = []
for string in strings:
if string != "":
result.append(string)
return result
def remove_empty_strings(strings):
return [string for string in strings if string != ""]
def remove_empty_strings(strings):
return list(filter(lambda string: string != "", strings))
可以通過調用這些函數來去除字符串中的空字符串,例如:
strings = ["hello", "", "world", "", "python"]
result = remove_empty_strings(strings)
print(result)
輸出:
['hello', 'world', 'python']