Check if a String Is a Palindrome in Python
- Check if a String Is Palindrome Using the List Slicing Method in Python
- Check if a String Is Palindrome Using the reversed() Function in Python
This tutorial discusses the methods to check if a string is a palindrome in Python.
Check if a String Is Palindrome Using the List Slicing Method in Python
A Palindrome string is a word that reads the same forwards and backwards. For example, the word madam remains the same if we reverse the sequence of letters in it; this type of word is called a Palindrome.
We can check for Palindrome strings by reversing the original string and comparing each element of the original string with each element of the reversed string; this can be done with list slicing. The following program below shows us how to check whether a string is a Palindrome or not with the list slicing method.
word = input() if str(word) == str(word)[::-1]: print("Palindrome") else: print("Not Palindrome")
ma#am Palindrome
We checked whether the string ma#am is a Palindrome or not with the list slicing method in the code above. We first calculated the reverse value of the original word with [::-1] as the list index. We then compared each index with the equality operator == . If both the original and reversed words match, we print Palindrome on the console; if not, we print Not Palindrome .
Check if a String Is Palindrome Using the reversed() Function in Python
The reversed() function takes a sequence of elements and returns a reverse iterator for that sequence. Since a string is a sequence of characters, we can also use the reversed() function in place of the [::-1] list index to reverse the sequence of characters inside a string. We can then compare both original string and reversed string, element-wise, to determine whether it’s a Palindrome or not. The following program snippet demonstrates how to check whether a string is a Palindrome or not with the reversed() function.
word = input() if str(word) == "".join(reversed(word)): print("Palindrome") else: print("Not Palindrome")
maisam Not Palindrome
We checked whether the string maisam is a Palindrome or not with the reversed() function in the program above. We first calculated the reverse form of the original word with «».join(reversed(word)) . After that, we compared both the original and the reversed word, element-wise, with the equality operator == . If both the original and reversed words match, we print Palindrome on the console; if not, we print Not Palindrome .
Maisam is a highly skilled and motivated Data Scientist. He has over 4 years of experience with Python programming language. He loves solving complex problems and sharing his results on the internet.
Related Article — Python String
- Remove Commas From String in Python
- Check a String Is Empty in a Pythonic Way
- Convert a String to Variable Name in Python
- Remove Whitespace From a String in Python
- Extract Numbers From a String in Python
- Convert String to Datetime in Python
Как определить является ли строка палиндромом python
Решить эту задачу можно многими способами, приведу самый простой — можно сравнить строку с перевернутой.
def is_palindrome(text): return text == text[::-1] is_palindrome('abb') # False is_palindrome('abba') # True
Проверка: является ли строка палиндромом?
Условие задачи: Дана строка, необходимо написать функцию, которая проверит является ли строка палиндромом или нет. Палиндром – это число, слово или фраза, одинаково читающиеся в обоих направления.
Например слово ‘radar’ ‘радар’.
Метод 1:
Найдем обратную строку с помощью метода reverse, затем сравним обратную строку с исходной
# возвращает обратную строку def reverse(s): return s[::-1] def is_palindrome(s): rev = reverse(s) # проверка на совпадение 2х строк if (s == rev): return True return False # запуск кода s = "malayalam" ans = is_palindrome(s) >>>True
Метод 2: Итеративный метод. Начать цикл с length/2 и проверять первый и последний элемент, второй и предпоследний и т.д. Если хоть что-то не совпадает, следовательно это не полиндром.
def isPalindrome(str): # Run loop from 0 to len/2 for i in xrange(0, len(str)/2): if str[i] != str[len(str)-i-1]: return False return True s = "malayalam" ans = isPalindrome(s) >>> True
Метод 3: Использование встроеной функции для реверса строки.
Просто посмотрите код.
def isPalindrome(s): # Используем встроенную функцию rev = ''.join(reversed(s)) # Проверяем строки на равенство if (s == rev): return True return False s = "malayalam" ans = isPalindrome(s) True
3 способа в вашу копилку питониста.
Если вы нашли ошибку в коде, пишите в комментариях.
Программа палиндрома на Python
Палиндром в Python – это число или буква, которые остаются неизменными, даже если число и буквы перевернуты.
121, 11, 414, 1221, 74747 – числа палиндрома.
MOM, DAD, MADAM, REFER – это буквы палиндрома.
JAVATPOINT, PROGRAM, JAVA – это не буквы палиндрома.
Алгоритм палиндрома
- Прочтите цифру или букву.
- Сохраните букву или цифру во временной переменной.
- Переверните букву или цифру.
- Сравните временную переменную с обратной буквой или цифрой.
- Если обе буквы или цифры совпадают, выведите «эта строка / число является палиндромом».
- Иначе напишите «эта строка / число не является палиндромом».
Примеры программ палиндрома на Python:
Программа 1: строка палиндрома
str = 'JaVaJ' str = str.casefold() # This string is reverse. rev = reversed(str) if list(str) == list(rev): print("PALINDROME !") else: print("NOT PALINDROME !")
PALINDROME !
Программа 2: строчная программа палиндрома
string=input(("Enter a letter:")) if(string==string[::-1]): print("The letter is a palindrome") else: print("The letter is not a palindrome")
Enter a letter: javatpoint The letter is not a palindrome Enter a letter: MADAM The letter is a palindrome
Программа 3: числовая программа-палиндром с использованием цикла while
Num = int(input("Enter a value:")) Temp = num Rev = 0 while(num > 0): dig = num % 10 rev = rev * 10 + dig num = num // 10 if(temp == rev): print("This value is a palindrome number!") else: print("This value is not a palindrome number!")
Enter the value: 2551 This value is not a palindrome number! Enter the value: 1221 This value is a palindrome number!
