如何在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