📌  相关文章
📜  Python -字符列表中的测试字符串,反之亦然

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

Python -字符列表中的测试字符串,反之亦然

给定一个字符串,检查它是否按顺序出现在字符列表中,反之亦然。

方法#1:在运算符+ join()中使用[字符列表中的字符串]

在此,我们使用 join() 将字符列表转换为字符串,并将其应用于运算符以测试子字符串是否存在。

Python3
# Python3 code to demonstrate working of
# Test String in Character List and vice-versa
# Using in operator and join() [String in list]
 
# initializing string
test_str = 'geeks'
 
# printing original string
print("The original string is : " + str(test_str))
 
# initializing Character list
K = ['g', 'e', 'e', 'k', 'f', 'o', 'r', 'g', 'e', 'e', 'k', 's']
 
# joining list
joined_list = ''.join(K)
 
# checking for presence
res = test_str in joined_list
 
# printing result
print("Is String present in character list : " + str(res))


Python3
# Python3 code to demonstrate working of
# Test String in Character List and vice-versa
# Using in operator + join() [ Character List in String ]
 
# initializing string
test_str = 'geeksforgeeks'
 
# printing original string
print("The original string is : " + str(test_str))
 
# initializing Character list
K = ['g', 'e', 'e', 'k', 's']
 
# joining list
joined_list = ''.join(K)
 
# checking for presence
res = joined_list in test_str
 
# printing result
print("Is character list present in String : " + str(res))


输出
The original string is : geeks
Is String present in character list : True

方法#2:在运算符+join()中使用[字符串中的字符列表]

在这种情况下,目标字符列表被转换为字符串,然后使用 in运算符检入字符串。

蟒蛇3

# Python3 code to demonstrate working of
# Test String in Character List and vice-versa
# Using in operator + join() [ Character List in String ]
 
# initializing string
test_str = 'geeksforgeeks'
 
# printing original string
print("The original string is : " + str(test_str))
 
# initializing Character list
K = ['g', 'e', 'e', 'k', 's']
 
# joining list
joined_list = ''.join(K)
 
# checking for presence
res = joined_list in test_str
 
# printing result
print("Is character list present in String : " + str(res))
输出
The original string is : geeksforgeeks
Is character list present in String : True