Skip to content

Python Program to find out all palindrome string from a text file

Python Program to find out all palindrome string from a text file

In this tutorial we will write a Python Program to find out all palindrome string from a text file . Before reading further we recommend to read about below tutorial-

I have a sample text file demo.txt in my working folder whose contents is shown below-

I love my mom and dad .

Python Program to find out all palindrome string from a text file

Steps

  • At first we will define a is_palindrome() function which will check if a given string is palindrome or not .
  • After that we will define another function find_all_palindrome() which will take the file name as function argument .
  • Inside this function we will open the file in read mode . After that using split() method we will split the file into list of words and store in a variable .
  • After that using filter() function we will extract all the palindrome string from the list and store it in a new variable .
  • At last we will return the variable .
# defining a function which will check 
# if the string is palindrome or not
def is_palindrome(mystring):
    mystring=mystring.lower()
    reverse=mystring[::-1]
    return mystring==reverse


def find_all_palindrome(filename):
    # opening the file
    with open(filename) as fp:
        # store the every word of the file in a list
        mylist=fp.read().split() 
        print(mylist) # this line is for our understanding
        # extracting all palindrome string
        mylist=list(filter(is_palindrome,mylist))
    return mylist  

print(find_all_palindrome("demo.txt"))
['I', 'love', 'my', 'mom', 'and', 'dad', '.']
['I', 'mom', 'dad', '.']
  • In the above code first we have defined is_palindrome() function which will return True if string is palindrome otherwise return False .
  • After that we have defined find_all_palindrome() which will take the file name as function argument .
  • Then we have opened the file in read mode .
  • After mylist=fp.read().split() line mylist is assigned with ['I', 'love', 'my', 'mom', 'and', 'dad', '.'] . We have also print the mylist inside the function to clear your understanding .
  • In mylist=list(filter(is_palindrome,mylist)) line filter() function has applied is_palindrome() function to the every string of the mylist . filter() function extracts all the palindrome string from mylist and return a filter-object . We have converted the filter-object to a list using list() function and stored in mylist variable .
  • After that we have returned the mylist variable .
  • At last we have called the find_all_palindrome() function with “demo,txt” Which has printed all the palindrome string from the file . As all the single word is palindrome so "I" and "." is also found in the list with "mom" and "dad" .

Thank you for reading this Article . If You enjoy it Please Share the article . If you want to say something Please Comment .

Leave a Reply