Page Contents
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-
- Python Program to check if a string is Palindrome or not
- File Handling in Python – An intro for Beginners
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 returnTrue
if string is palindrome otherwise returnFalse
. - 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()
linemylist
is assigned with['I', 'love', 'my', 'mom', 'and', 'dad', '.']
. We have also print themylist
inside the function to clear your understanding . - In
mylist=list(filter(is_palindrome,mylist))
linefilter()
function has appliedis_palindrome()
function to the every string of themylist
.filter()
function extracts all the palindrome string frommylist
and return a filter-object . We have converted the filter-object to a list usinglist()
function and stored inmylist
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 .