共計(jì) 477 個(gè)字符,預(yù)計(jì)需要花費(fèi) 2 分鐘才能閱讀完成。
有幾種方法可以去除字符串中的空字符串:
- 使用循環(huán)和條件語(yǔ)句:
def remove_empty_strings(strings):
result = []
for string in strings:
if string != "":
result.append(string)
return result
- 使用列表推導(dǎo)式:
def remove_empty_strings(strings):
return [string for string in strings if string != ""]
- 使用 filter 函數(shù):
def remove_empty_strings(strings):
return list(filter(lambda string: string != "", strings))
可以通過(guò)調(diào)用這些函數(shù)來(lái)去除字符串中的空字符串,例如:
strings = ["hello", "", "world", "", "python"]
result = remove_empty_strings(strings)
print(result)
輸出:
['hello', 'world', 'python']
丸趣 TV 網(wǎng) – 提供最優(yōu)質(zhì)的資源集合!
正文完