contains() 方法是 Python String 類的一個方法,可以用來檢查該類是否包含另一個字元串。此外,以下劃線開頭的方法據說是 Python 中的私有方法,包含 __() 方法也是如此。然而,有些開發人員避免在代碼中使用這些私有方法。
但是現在,讓我們探索一下 Python 字元串中 包含 __() 方法的一些基本原理。
Python 字元串包含
在 [Python 字元串](https://www.javatpoint.com/python-strings) 中包含 __() 方法是一個實例方法,它根據字元串對象是否具有特定的字元串對象的條件,將布爾值返回為真或假。
注意:Python 字元串中的 contains()方法區分大小寫。
下面是 Python 字元串 包含 __() 方法的一些基本示例:
例 1:
my_string = 'welcome'
print("my string contains \'w\' =", my_string.__contains__('w'))
print("my string contains \'W\' =", my_string.__contains__('W'))
print("my string contains \'a\' =", my_string.__contains__('a'))
print("my string contains \'c\' =", my_string.__contains__('c'))
print("my string contains \'E\' =", my_string.__contains__('w'))
輸出:
my string contains 'w' = True
my string contains 'W' = False
my string contains 'a' = False
my string contains 'c' = True
my string contains 'E' = True
說明:
在上面的程序中,我們已經創建了一個字元串作為 my_string 。然後,我們使用 Python 字元串 contains() 方法來檢查給定的字元串對象是否在字元串中。例如,我們已經檢查了『w』是否出現在『歡迎』字元串中,結果,它返回 True。同樣,對於「W」、「a」和「E」,輸出結果分別為假。
除了上面的例子之外, 包含 __() 方法的功能也類似於 str 類方法。
讓我們考慮下面的例子來理解它的行為:
示例:
print(str.__contains__('WELCOME', 'W'))
print(str.__contains__('WELCOME', 'A'))
輸出:
True
False
說明:
在上面的例子中,我們使用了 contains() 方法,就像 str 類方法一樣,並檢查字元串中是否存在給定的字元串對象。
讓我們理解另一個例子,其中我們將要求用戶輸入兩個字元串,並檢查第二個字元串是否是第一個字元串的一部分。
示例:
first_string = input('Please input the first input string:\n')
second_string = input('Please input the second input string:\n')
print('Checking if the second string is a part of first string?:', first_string.__contains__(second_string))
輸出:
Please input the first input string:
Hey there! This is my Computer.
Please input the second input string:
Comp
Checking if the second string is a part of first string?: True
說明:
在上面的例子中,我們要求用戶使用 input() 方法輸入兩個不同的字元串。最後,我們使用 contains() 方法來檢查第二個字元串是否是第一個字元串的一部分。結果,用戶向程序提供輸入,程序執行該功能以檢查結果。
原創文章,作者:小藍,如若轉載,請註明出處:https://www.506064.com/zh-tw/n/254342.html