当需要测试字符列表中的字符串时,反之亦然,使用简单的“in”运算符和“join”方法。
以下是相同的演示 -
my_string = 'python' print("字符串是:") print(my_string) my_key = ['p', 'y', 't', 'h', 'o', 'n', 't', 'e', 's', 't'] print("关键是 ") print(my_key) joined_list = ''.join(my_key) my_result = my_string in joined_list print("结果是:") if(my_result == True): print("The string is present in the character list") else: print("The string is not present in the character list")输出结果
字符串是: python 关键是 ['p', 'y', 't', 'h', 'o', 'n', 't', 'e', 's', 't'] 结果是: The string is present in the character list
一个字符串被定义并显示在控制台上。
键的值已定义并显示在控制台上。
使用 将键的元素连接起来形成一个字符串。join()功能。
这被分配给一个变量。
比较字符串和键以查看字符串是否存在于上述列表中。
这个结果被分配给一个变量。
根据此结果中的布尔值,在控制台上显示相关消息。