Python 有字串“包含”子字串的方法嗎?


在 Python 中,子字串是出現在較長字串中的字元序列。例如,在字串“Hello, world!”中,子字串“world”出現在較長字串中。

子字串可以是一個字元,也可以是更長的字元序列。當您需要提取或操作字串的特定部分時,子字串很有用。您還可以使用 Python 的字串方法檢查子字串是否包含在較長字串中。

Python 提供了一個內建方法來檢查字串是否包含子字串。該方法稱為“in”,如果在字串中找到子字串,則返回布林值 True,否則返回 False。

以下是一些關於如何使用 in 方法檢查字串是否包含子字串的示例

示例

在此示例中,我們定義了一個字串“Lorem Ipsum”,並檢查它是否包含子字串“Lorem”。由於找到了子字串,程式列印“子字串已找到!”。

# Define a string
text = "Lorem Ipsum"
# Check if the string contains a substring
if "Lorem" in text:
    print("Substring found!")
else:
    print("Substring not found.")

輸出

Substring found!

示例

在此示例中,我們定義了一個字串“This is a test string”,並檢查它是否包含子字串“test”。由於找到了子字串,程式列印“子字串已找到!”。

# Define a string
text = "This is a test string"

# Check if the string contains a substring
if "test" in text:
    print("Substring found!")
else:
    print("Substring not found.")

輸出

Substring found!

示例

在此示例中,我們定義了一個字串“Python is a great coding language”,並檢查它是否包含子字串“Javascript”。由於未找到子字串,程式列印“未找到子字串”。

# Define a string
text = "Python is a great coding language"
# Check if the string contains a substring
if "Javascript" in text:
    print("Substring found!")
else:
    print("Substring not found.")

輸出

Substring not found.

示例

在此示例中,我們定義了一個字串“The wild horse jumps over the fence”,並檢查它是否包含子字串“black”。由於未找到子字串,程式列印“未找到子字串”。

# Define a string
text = "The wild horse jumps over the fence"
# Check if the string contains a substring
if "black" in text:
    print("Substring found!")
else:
    print("Substring not found.")

輸出

Substring not found

示例

在此示例中,我們定義了一個字串“I love to code in Python”,並檢查它是否包含子字串“code”。由於找到了子字串,程式列印“子字串已找到!”。

# Define a string
text = "I love to code in Python"
# Check if the string contains a substring
if "code" in text:
    print("Substring found!")
else:
    print("Substring not found.")

輸出

Substring found!

示例

在此示例中,我們定義了一個字串“Python is an interpreted high-level programming language”,並檢查它是否包含子字串“interpreted”。由於找到了子字串,程式列印“子字串已找到!”。

# Define a string
text = "Python is an interpreted high-level programming language"
# Check if the string contains a substring
if "interpreted" in text:
    print("Substring found!")
else:
    print("Substring not found.")

輸出

Substring found!

更新於: 2023年8月10日

390 次檢視

開啟你的 職業生涯

透過完成課程獲得認證

開始學習
廣告

© . All rights reserved.