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