📌  相关文章
📜  用于检查字符串中特定字符的Python程序

📅  最后修改于: 2022-05-13 01:55:03.356000             🧑  作者: Mango

用于检查字符串中特定字符的Python程序

给定一个字符串's' 和字符数组 'arr',任务是编写一个Python程序来检查字符串s 中字符数组 arr 中的字符。

例子:

Input: s = @geeksforgeeks%
       arr[] = {'o','e','%'}
Output: [true,true,true]

Input: s = $geek
       arr[] = {'@','e','a','$'} 
Output: [false,true,false,true]

方法#1:在关键字+循环中使用

遍历 char 数组,对于 arr 中的每个字符,使用返回布尔值(真或假)的 in运算符检查字符串s 中是否存在该字符。

Python3
# Python implementation to check string
# for specific characters
  
# function to check string
def check(s, arr):
    result = []
    for i in arr:
        
        # for every character in char array
        # if it is present in string return true else false
        if i in s:
            result.append("True")
        else:
            result.append("False")
    return result
  
  
# Driver Code
s = "@geeksforgeeks123"
arr = ['e', 'r', '1', '7']
print(check(s, arr))


Python3
# Python implementation to check string for
# specific characters
  
# function to check string
def check(s, arr):
    
    # returns a list of booleans
    result = [characters in s for characters in arr]
    return result
  
  
# Driver Code
s = "@geeksforgeeks123"
arr = ['e', 'r', '1', '@', '0']
print(check(s, arr))


输出
['True', 'True', 'True', 'False']

方法#2:替代方法

蟒蛇3

# Python implementation to check string for
# specific characters
  
# function to check string
def check(s, arr):
    
    # returns a list of booleans
    result = [characters in s for characters in arr]
    return result
  
  
# Driver Code
s = "@geeksforgeeks123"
arr = ['e', 'r', '1', '@', '0']
print(check(s, arr))
输出
[True, True, True, True, False]