首頁  >  文章  >  後端開發  >  python怎麼去除空字串

python怎麼去除空字串

王林
王林轉載
2024-03-02 08:34:02448瀏覽

python怎麼去除空字串

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

  1. 使用迴圈和條件語句:
def remove_empty_strings(strings):
result = []
for string in strings:
if string != "":
result.append(string)
return result
  1. 使用列表推導式:
def remove_empty_strings(strings):
return [string for string in strings if string != ""]
  1. 使用filter函數:
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']

以上是python怎麼去除空字串的詳細內容。更多資訊請關注PHP中文網其他相關文章!

陳述:
本文轉載於:lsjlt.com。如有侵權,請聯絡admin@php.cn刪除