首頁 > 後端開發 > Python教學 > 如何檢查Python字串是否包含子字串?

如何檢查Python字串是否包含子字串?

Mary-Kate Olsen
發布: 2024-12-22 10:48:11
原創
880 人瀏覽過

How Can I Check if a Python String Contains a Substring?

Python 字串包含子字串方法

Python 中沒有專門的string.contains() 或string.indexof() 方法來檢查字串是否包含子字串。但是,還有其他方法可以實現此功能。

使用 'in' 運算子

'in' 運算子可用來測試字串中是否存在子字串。它將子字串與整個字串進行比較,如果找到則傳回 True。

if "blah" in some_string:
    # Code to be executed if "blah" is in some_string
else:
    # Code to be executed if "blah" is not in some_string
登入後複製

注意: 'in' 運算子區分大小寫。

其他替代方案

  • string.find()方法: 傳回子字串第一次出現的索引,如果沒有找到,則返回-1。

    index = some_string.find("blah")
    登入後複製
  • string.startswith() 方法: 檢查字串是否以指定的開頭substring.

    if some_string.startswith("blah"):
      # Code to be executed if some_string starts with "blah"
    登入後複製
  • string.endswith()方法:

    檢查字串是否以指定的子字串結尾。
    if some_string.endswith("blah"):
      # Code to be executed if some_string ends with "blah"
    登入後複製

以上是如何檢查Python字串是否包含子字串?的詳細內容。更多資訊請關注PHP中文網其他相關文章!

本網站聲明
本文內容由網友自願投稿,版權歸原作者所有。本站不承擔相應的法律責任。如發現涉嫌抄襲或侵權的內容,請聯絡admin@php.cn
作者最新文章
熱門教學
更多>
最新下載
更多>
網站特效
網站源碼
網站素材
前端模板