Python One-Liner: Validate Palindrome Ignoring Non-Alphanumerics

Quickly check if a string is a palindrome in one line, ignoring non-alphanumeric characters, with two simple methods. 🪞

Python One-Liner: Validate Palindrome Ignoring Non-Alphanumerics
CodeVisium
1.1K views • Apr 12, 2025
Python One-Liner: Validate Palindrome Ignoring Non-Alphanumerics

About this video

🪞 Check if a String is a Valid Palindrome in One Line!

This script demonstrates two methods for verifying whether a given string is a valid palindrome—ignoring punctuation, spaces, and case. A palindrome is a string that reads the same forwards and backwards (e.g., "A man, a plan, a canal: Panama").

Long Way Explanation:

Import the Regex Module:

import re imports Python's regular expression module, which is used to manipulate the string.

Define is_valid_palindrome(s):

Filtering the String:

re.sub(r'[^a-zA-Z0-9]', '', s) removes any character that is not a letter or digit.

.lower() converts the string to lowercase to ignore case differences.

Palindrome Check:

The filtered string is compared to its reverse (filtered[::-1]). If they match, the string is a palindrome.

Usage Example:

The function is called with "A man, a plan, a canal: Panama", and it returns True because, after filtering, the string reads the same forwards and backwards.

One-Liner Explanation:

Inline String Filtering & Palindrome Check:

The one-liner imports re and immediately applies a lambda function to perform the palindrome check:

re.sub(r'[^a-zA-Z0-9]', '', "A man, a plan, a canal: Panama").lower() filters and normalizes the string.

The lambda (lambda s: s == s[::-1]) then checks if the processed string is equal to its reverse.

Output:

The result is printed directly, confirming whether the string is a valid palindrome.

This example is a perfect demonstration of Python's power to solve text processing problems both in a readable, step-by-step manner and in a compact one-liner—ideal for interviews and quick utility scripts!

Codes:

📌 Long Way:

import re

def is_valid_palindrome(s):
# Remove all non-alphanumeric characters and convert to lowercase
filtered = re.sub(r'[^a-zA-Z0-9]', '', s).lower()
# Check if the filtered string is the same forwards and backwards
return filtered == filtered[::-1]

# Example usage:
test_string = "A man, a plan, a canal: Panama"
print(is_valid_palindrome(test_string))

# Output: True

📌 One-Liner:

import re; print((lambda s: s == s[::-1])(re.sub(r'[^a-zA-Z0-9]', '', "A man, a plan, a canal: Panama").lower()))

# Output: True

Tags and Topics

Browse our collection to discover more content in these categories.

Video Information

Views

1.1K

Likes

9

Duration

0:10

Published

Apr 12, 2025

User Reviews

4.1
(1)
Rate:

Related Trending Topics

LIVE TRENDS

Related trending topics. Click any trend to explore more videos.