如何在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
廣告
資料結構
網路
關係資料庫管理系統(RDBMS)
作業系統
Java
iOS
HTML
CSS
Android
Python
C語言程式設計
C++
C#
MongoDB
MySQL
Javascript
PHP