Examples
- Palindrome Program in Python (Check String is Palindrome or Not)
- Program to Remove Punctuations From String in Python
- Remove a Character from String in Python (Program With Examples)
- Remove Stop Words from String in Python Using NLTK and spaCy
- Program to Sort Words in Alphabetical Order in Python (Arrange in Alphabetic Order)
- How to Sort Strings in Python? (Program With Examples)
- How to Count Vowels in Python String? Vowels Program in Python
- How to Remove Vowels from String in Python? Program With Examples
- How to Convert String to Int or Float in Python? String Parse Program
- How to Convert Float to Int in Python? Program With Examples
- How to Convert Int to String in Python? Program with Examples
- Remove Spaces from String in Python (Trim Whitespace)
- Python Program to Check If Two Strings are Anagram
- How to Capitalize First Letter in Python? String Capitalization Program
- Find All Permutations of String in Python (Programs and Examples)
- Find All Substrings of a String in Python (Programs with Examples)
- Create Multiline String in Python (With & Without New Line)
Palindrome Program in Python (Check String is Palindrome or Not)
In this tutorial, you will learn how to check if a string is palindrome or not in Python. A palindrome is a word, phrase, number, or sequence of characters that reads the same forwards and backwards. This program provides multiple approaches to determine whether a given string is a palindrome or not, catering to programmers of all levels of expertise.
Palindrome Logic in Python
The logic to check if a string or number is a palindrome in Python revolves around comparing the characters or digits from both ends.
For a string:
- Convert the string to lowercase (if case-insensitive) and remove any whitespace or punctuation.
- Compare the characters at the corresponding positions from the start and end of the string.
- If at any point the characters don't match, the string is not a palindrome.
- If all the characters match until the midpoint of the string, the string is a palindrome.
For a number:
- Convert the number to a string representation.
- Apply the same logic as for a string by comparing the characters at corresponding positions.
As a programmer, you may encounter situations where you need to use the Python code for palindrome number or string to find whether the given string or number is palindrome or not. This can be useful in various scenarios, such as:
- Data Validation: The palindrome program in Python can be used in applications that require input validation, such as usernames, passwords, or other sensitive information. Verifying it helps you to ensure the validity and integrity of user input.
- Algorithmic Challenges: Palindrome-related problems often appear in coding interviews or algorithmic competitions. Being able to efficiently identify palindromes is crucial in solving these challenges and optimizing your code for performance.
- Text Manipulation: Python palindrome program can be valuable when working with textual data. For instance, it can aid in tasks such as parsing and analyzing strings, identifying patterns, or extracting relevant information from a text corpus.
Now, let's dive into the different approaches you can use to check if a string is palindrome or not in Python. Whether you prefer using functions, for loops, or any other technique, this tutorial has got you covered.
By the end, you'll have a solid understanding of various methods to tackle this problem, empowering you to write more efficient and elegant code. You can practice the given programs with the Python online compiler.
Let's get started!
Python Program to Find Palindrome Number
Code
Here's a Python program to print palindrome numbers in a range:
def is_palindrome(number):
# Convert the number to a string
number_str = str(number)
# Check if the string and its reverse are equal
if number_str == number_str[::-1]:
return True
else:
return False
def find_palindrome_numbers(start, end):
palindrome_numbers = []
for number in range(start, end+1):
if is_palindrome(number):
palindrome_numbers.append(number)
return palindrome_numbers
# Test the function
start_number = int(input("Enter the starting number: "))
end_number = int(input("Enter the ending number: "))
palindromes = find_palindrome_numbers(start_number, end_number)
print("Palindrome numbers:", palindromes)
Output
Enter the starting number: 1
Enter the ending number: 999
Palindrome numbers: [1, 2, 3, 4, 5, 6, 7, 8, 9, 11, 22, 33, 44, 55, 66, 77, 88, 99, 101, 111, 121, 131, 141, 151, 161, 171, 181, 191, 202, 212, 222, 232, 242, 252, 262, 272, 282, 292, 303, 313, 323, 333, 343, 353, 363, 373, 383, 393, 404, 414, 424, 434, 444, 454, 464, 474, 484, 494, 505, 515, 525, 535, 545, 555, 565, 575, 585, 595, 606, 616, 626, 636, 646, 656, 666, 676, 686, 696, 707, 717, 727, 737, 747, 757, 767, 777, 787, 797, 808, 818, 828, 838, 848, 858, 868, 878, 888, 898, 909, 919, 929, 939, 949, 959, 969, 979, 989, 999]
Explanation
In this program, we have two functions. The first function, is_palindrome, takes a number as an argument. It converts the number to a string and checks if the string and its reverse are equal. If they are, the function returns True, indicating that the number is a palindrome. Otherwise, it returns False.
The second function, find_palindrome_numbers, takes a starting number and an ending number as arguments. It iterates through all the numbers from the starting number to the ending number using a for loop. For each number, it calls the is_palindrome function to check if it is a palindrome. If a number is a palindrome, it adds it to the palindrome_numbers list. Finally, the function returns the list of palindrome numbers.To use the program, the user is prompted to enter the starting and ending numbers. The find_palindrome_numbers function is called with the input numbers as arguments. The resulting palindrome numbers within the given range are then displayed.
String Palindrome Program in Python (Using Function)
Here's a palindrome program in Python using function:
Code
def is_palindrome(string):
# Convert the string to lowercase and remove spaces
string = string.lower().replace(" ", "")
# Reverse the string
reversed_string = string[::-1]
# Check if the string and its reverse are equal
if string == reversed_string:
return True
else:
return False
# Test the function
input_string = input("Enter a string: ")
if is_palindrome(input_string):
print("The string is a palindrome.")
else:
print("The string is not a palindrome.")
Output
Enter a string: tutorialsfreak
The string is not a palindrome.
Explanation
-
In this program, we define a function called is_palindrome that takes a string as an argument.
-
The function first converts the string to lowercase and removes any spaces. It then creates a reversed version of the string using slicing.
-
Finally, it compares the original string with the reversed string to determine if they are equal.
To use the program, the user is prompted to enter a string. The is_palindrome function is then called with the input string as the argument. Based on the return value, the program displays whether the string is a palindrome or not in Python.
Palindrome String Program in Python Using for loop
Here's the program to check palindrome number in Python using for loop:
Code
def is_palindrome(string):
# Convert the string to lowercase and remove spaces
string = string.lower().replace(" ", "")
# Iterate over the string using a for loop
for i in range(len(string)//2):
if string[i] != string[-(i+1)]:
return False
return True
# Test the function
input_string = input("Enter a string: ")
if is_palindrome(input_string):
print("The string is a palindrome.")
else:
print("The string is not a palindrome.")
Output
Enter a string: 16461
The string is a palindrome.
Explanation
-
In this program, the is_palindrome function takes a string as an argument. It first converts the string to lowercase and removes any spaces.
-
Then, using a for loop, it iterates over the first half of the string. For each character, it compares it with the corresponding character from the end of the string.
-
If any pair of characters doesn't match, the function returns False, indicating that the string is not a palindrome. If the loop completes without any mismatches, the function returns True, indicating that the string is a palindrome.
Similar to the previous program, the user is prompted to enter a string, and the is_palindrome function is called with the input string as the argument. Based on the return value, the program displays whether the string is a palindrome or not.
Palindrome String Program in Python Using while loop
Here's a program to check string palindrome in Python using while loop:
Code
def is_palindrome(string):
# Convert the string to lowercase and remove spaces
string = string.lower().replace(" ", "")
# Initialize the loop variables
left = 0
right = len(string) - 1
# Iterate using a while loop until the pointers meet
while left < right:
if string[left] != string[right]:
return False
left += 1
right -= 1
return True
# Test the function
input_string = input("Enter a string: ")
if is_palindrome(input_string):
print("The string is a palindrome.")
else:
print("The string is not a palindrome.")
Output
Enter a string: 979
The string is a palindrome.
Explanation
In this program, the is_palindrome function takes a string as an argument. It converts the string to lowercase and removes any spaces. It then initializes two pointers, left and right, which point to the first and last characters of the string, respectively.
The program uses a while loop to compare characters from both ends of the string. Inside the loop, it checks if the characters at the current pointers are different. If they are, it returns False, indicating that the string is not a palindrome. Otherwise, it increments the left pointer and decrements the right pointer to move towards the center of the string.
The loop continues until the left pointer becomes greater than or equal to the right pointer. If the loop completes without returning False, it means that all the characters matched, and the string or number is a palindrome. In that case, the function returns True.As with the previous examples, the user is prompted to enter a string, and the is_palindrome function is called with the input string as the argument. Based on the return value, the program displays whether the string is a palindrome or not.
Check Next Palindrome Number in Python
Sure! Here's the Python program to find the next palindrome number:
Code
def is_palindrome(number):
# Convert the number to a string
number_str = str(number)
# Check if the string and its reverse are equal
if number_str == number_str[::-1]:
return True
else:
return False
def find_next_palindrome(number):
next_number = number + 1
while not is_palindrome(next_number):
next_number += 1
return next_number
# Test the function
input_number = int(input("Enter a number: "))
next_palindrome = find_next_palindrome(input_number)
print("The next palindrome number is:", next_palindrome)
Output
Enter a number: 9999
The next palindrome number is: 10001
Explanation
-
In this program, we define two functions. The first function, is_palindrome, takes a number as an argument. It converts the number to a string and checks if the string and its reverse are equal. If they are, the function returns True, indicating that the number is a palindrome. Otherwise, it returns False.
-
The second function, find_next_palindrome, takes a number as an argument. It starts by initializing a variable, next_number, with the given number incremented by 1. It then enters a while loop, which continues until the next_number is a palindrome.
-
Inside the loop, it increments the next_number by 1 and checks if it is a palindrome using the is_palindrome function. Once a palindrome number is found, the loop terminates, and the function returns the next_number.