如何在Python中掃描字串以查詢特定字元?


在本文中,我們將瞭解如何在Python中掃描字串以查詢特定字元。

第一種方法是使用“in”關鍵字。我們可以使用“in”關鍵字來檢查字串中是否存在某個字元。如果它存在於字串中,則返回True,否則返回False。

in”關鍵字也用於在for迴圈中迭代序列,它也用於迭代序列,例如列表、元組和字串或其他可迭代物件。

示例1

在下面的示例中,我們以字串作為輸入,並使用“in”運算子檢查特定字元是否存在於字串中。

str1 = "Welcome to Tutorialspoint"
char = 'T'

print("The given string is")
print(str1)

print("The given character is")
print(char)

print("Checking if the character is present in the string")
print(char in str1)

輸出

上述示例的輸出如下:

The given string is
Welcome to Tutorialspoint
The given character is
T
Checking if the character is present in the string
True

示例2

在下面的示例中,我們使用與上述相同的程式,但我們使用不同的輸入並檢查特定字元是否存在於字串中。

str1 = "Welcome to Tutorialspoint"
char = 'z'

print("The given string is")
print(str1)

print("The given character is")
print(char)

print("Checking if the character is present in the string")
print(char in str1)

輸出

上述示例的輸出如下:

The given string is
Welcome to Tutorialspoint
The given character is
z
Checking if the character is present in the string
False

使用集合

第二種方法是使用集合。我們將使用一組字元,並使用“any”方法檢查集合中的任何字元是否存在於字串中。如果集合中的任何字元存在於字串中,此方法將返回True,否則返回False。

示例1

在下面的示例中,我們以字串和一組字元作為輸入,並檢查字串中是否存在任何字元。

str1 = "Welcome to Tutorialspoint123"
chars = set('0123456789$,')

print("The given string is")
print(str1)

print("The given character is")
print(chars)

print("Checking if any of the characters is present in the string")
print(any((c in chars) for c in str1))

輸出

上述示例的輸出如下:

The given string is
Welcome to Tutorialspoint123
The given character is
{'9', '1', ',', '5', '$', '3', '7', '2', '0', '6', '8', '4'}
Checking if any of the characters is present in the string
True

示例2

在下面的示例中,我們使用與上述相同的程式,但使用不同的輸入字串並檢查字串是否包含給定的字元。

str1 = "Welcome to Tutorialspoint"
chars = set('0123456789$,')

print("The given string is")
print(str1)

print("The given character is")
print(chars)

print("Checking if any of the characters is present in the string")
print(any((c in chars) for c in str1))

輸出

以下程式的輸出為:

The given string is
Welcome to Tutorialspoint
The given character is
{'5', ',', '6', '2', '0', '3', '$', '1', '7', '8', '9', '4'}
Checking if any of the characters is present in the string
False

更新於:2022年12月7日

4K+ 次瀏覽

啟動你的職業生涯

透過完成課程獲得認證

開始學習
廣告