Python – Strings with all given List characters


When it is required to find the strings which have all the given characters present in a list, a method is defined that takes the string as a parameter and iterates through the string, and adds the index value to it.

Example

Below is a demonstration of the same −

print("Method definition begins...")
def convert_to_my_string(my_string):
   my_result = ""
   for index in my_string:
      my_result += index

   return my_result
print("Method definition ends...")
my_string = ['L','e','a','r','n','P','y','t','h','o','n', 'c', 'o', 'o', 'l', 'f', 'u', 'n']

print("The list is : " )
print(my_string) 

print("The resultant string is : ")
print(convert_to_my_string(my_string))

Output

Method definition begins...
Method definition ends...
The list is :
['L', 'e', 'a', 'r', 'n', 'P', 'y', 't', 'h', 'o', 'n', 'c', 'o', 'o', 'l', 'f', 'u', 'n']
The resultant string is :
LearnPythoncoolfun

Explanation

  • A method named ‘convert_to_my_string’ is defined that takes a string as a parameter.

  • An empty string is defined.

  • The original parameter is iterated over, and the element is added to the empty string.

  • This is returned as output.

  • Outside the method, a list of characters is defined and is displayed on the console.

  • The method is called by passing every character to it.

  • The result is displayed as the output on the console.

Updated on: 13-Sep-2021

177 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements