溫馨提示×

python怎么去除空字符串

小億
85
2023-10-31 20:44:56
欄目: 編程語言

有幾種方法可以去除字符串中的空字符串:

  1. 使用循環(huán)和條件語句:
def remove_empty_strings(strings):
    result = []
    for string in strings:
        if string != "":
            result.append(string)
    return result
  1. 使用列表推導(dǎo)式:
def remove_empty_strings(strings):
    return [string for string in strings if string != ""]
  1. 使用filter函數(shù):
def remove_empty_strings(strings):
    return list(filter(lambda string: string != "", strings))

可以通過調(diào)用這些函數(shù)來去除字符串中的空字符串,例如:

strings = ["hello", "", "world", "", "python"]
result = remove_empty_strings(strings)
print(result)

輸出:

['hello', 'world', 'python']

0