Last modified: Feb 06, 2026 By Alexander Williams
Find Palindromes in Text File with Python
Working with text files is a common task in programming. You might need to analyze text for specific patterns. One interesting pattern is the palindrome.
A palindrome is a word, phrase, or sequence that reads the same forwards and backwards. Examples include "racecar" and "madam". Finding them manually in a large file is tedious.
Python makes this task simple. This guide will show you how to write a script to find all palindromes in a text file.
What You Will Need
To follow this tutorial, you need Python installed on your computer. You also need a basic text editor or an IDE like VS Code or PyCharm.
You should understand basic Python concepts. These include variables, loops, functions, and file handling. If you need help running your script, see our guide on How to Run Python File in Terminal.
Finally, create a text file named sample.txt with some content. We will use it for testing.
Understanding the Core Palindrome Logic
The heart of the solution is a function to check if a string is a palindrome. The logic is straightforward. We compare the string to its reverse.
We must also handle case sensitivity and ignore punctuation. The string "Racecar" should be identified as a palindrome.
We will use Python's string slicing to reverse a string. The syntax string[::-1] creates a reversed copy.
Writing the Check Function
Let's create a function named is_palindrome. It will take a word as input and return True or False.
def is_palindrome(word):
"""
Checks if a given string is a palindrome.
Converts to lowercase and removes non-alphanumeric characters.
Returns True if it reads the same forwards and backwards.
"""
# Clean the word: lower case and keep only letters/numbers
cleaned_word = ''.join(char.lower() for char in word if char.isalnum())
# Compare the cleaned word with its reverse
return cleaned_word == cleaned_word[::-1]
This function first cleans the input. The .isalnum() method keeps only letters and numbers. It removes spaces, punctuation, and symbols.
Then it converts everything to lowercase using .lower(). Finally, it checks if the cleaned string equals its reverse.
Reading Text from a File
Python has built-in functions for file handling. We will use the open() function in a with block. This ensures the file closes properly.
We need to read the file's content and split it into individual words. The .split() method is perfect for this.
def find_palindromes_in_file(filepath):
"""
Reads a text file and returns a list of palindromes found.
"""
palindromes = []
try:
with open(filepath, 'r') as file:
content = file.read()
# Split content into words
words = content.split()
for word in words:
if is_palindrome(word):
palindromes.append(word)
except FileNotFoundError:
print(f"Error: The file '{filepath}' was not found.")
return []
return palindromes
This function opens the file, reads all text, and splits it by whitespace. It then loops through each word. It uses our is_palindrome function to test each one.
Found palindromes are added to a list. The function includes error handling for a missing file.
Putting It All Together: The Complete Script
Now, let's combine the functions into a complete, working script. We'll add a main section to run the program.
def is_palindrome(word):
cleaned_word = ''.join(char.lower() for char in word if char.isalnum())
return cleaned_word == cleaned_word[::-1]
def find_palindromes_in_file(filepath):
palindromes = []
try:
with open(filepath, 'r') as file:
content = file.read()
words = content.split()
for word in words:
if is_palindrome(word):
palindromes.append(word)
except FileNotFoundError:
print(f"Error: The file '{filepath}' was not found.")
return []
return palindromes
if __name__ == "__main__":
# Specify your text file path here
input_file = "sample.txt"
result = find_palindromes_in_file(input_file)
if result:
print(f"Found {len(result)} palindrome(s) in '{input_file}':")
for p in result:
print(f" - {p}")
else:
print(f"No palindromes found in '{input_file}' or file was missing.")
Testing the Script with Example Output
Create a file named sample.txt with the following content:
Hello world! Racecar is a cool palindrome. So is madam. Don't forget noon. 12321 is a number palindrome. Python is fun.
Save the script as find_palindromes.py. Run it from your terminal. You should see output similar to this:
Found 5 palindrome(s) in 'sample.txt':
- Racecar
- madam
- noon
- 12321
- a
The script successfully finds "Racecar", "madam", "noon", and "12321". Notice it also finds the single letter "a" from the word "a". This is technically correct but may not be useful.
You can modify the logic to filter out single-character palindromes if needed.
Enhancing the Script for Better Results
The basic script works well. But we can improve it for real-world text. Text often contains punctuation attached to words.
For example, "madam." with a period would not be found by our simple split. We need to clean the words before checking.
We can use the re module (regular expressions) to extract words more accurately. This handles punctuation like commas, periods, and quotes.
import re
def find_palindromes_enhanced(filepath):
palindromes = []
try:
with open(filepath, 'r') as file:
content = file.read()
# Use regex to find all sequences of letters and numbers
words = re.findall(r'\b\w+\b', content)
for word in words:
if is_palindrome(word):
palindromes.append(word)
except FileNotFoundError:
print(f"Error: File '{filepath}' not found.")
return []
return palindromes
The regex pattern \b\w+\b finds all "word" characters (letters, digits, underscores) surrounded by word boundaries. This is more robust than simple splitting.
Remember to import the re module at the top of your script.
Conclusion
Finding palindromes in a text file is an excellent Python exercise. It combines file I/O, string manipulation, and basic logic.
You learned how to write a core checking function. You learned how to read a file and process its words. You also saw how to enhance the script for better accuracy.
The key steps are: clean the text, reverse it, and compare. This fundamental pattern is useful for many text analysis tasks.
You can now adapt this script for your own projects. Try finding palindromes in a webpage or a large book file. Experiment with different cleaning rules.
For more practice, consider modifying the script to find phrasal palindromes (like "A man, a plan, a canal: Panama"). This is a great next challenge. Remember, mastering file operations is crucial. If you're unsure how to execute your scripts, revisit our tutorial on How to Run Python File in Terminal.
Happy coding!