如何從 Python 元組中 grep 特定關鍵字?


如果你有一個字串元組並想搜尋特定的字串,你可以使用 in 運算子 。

示例

tpl = ("Hello", "world", "Foo", "bar")
print("world" in tpl)

輸出

這將輸出 -

True

示例

如果你想檢查是否存在子字串。你可以迴圈遍歷元組並使用以下方法查詢

tpl = ("Hello", "world", "Foo", "bar")
for i in tpl:
   if "orld" in i:
      print("Found orld in " + i )

輸出

這將輸出 -

Found orld in world

更新於:05-03-2020

185 次瀏覽

開啟你的 職業生涯

完成課程即可獲得認證

開始學習
廣告