When it is required to test string in character list and vice-versa, a simple ‘in’ operator and ‘join’ method are used.
Below is a demonstration of the same −
Example
my_string = 'python' print("The string is :") print(my_string) my_key = ['p', 'y', 't', 'h', 'o', 'n', 't', 'e', 's', 't'] print("The key is ") print(my_key) joined_list = ''.join(my_key) my_result = my_string in joined_list print("The result is :") if(my_result == True): print("The string is present in the character list") else: print("The string is not present in the character list")
Output
The string is : python The key is ['p', 'y', 't', 'h', 'o', 'n', 't', 'e', 's', 't'] The result is : The string is present in the character list
Explanation
A string is defined and displayed on the console.
The value for key is defined and displayed on the console.
The elements of the key are joined to make a string using .join() function.
This is assigned to a variable.
The string and the key are compared to see if string is present in the above mentioned list.
This result is assigned to a variable.
Based on the Boolean value in this result, the relevant message is displayed on the console.