How to identify if a string is a palindrome?

5

A palindrome is a word or phrase that has the property of being read from right to left or from left to right. For example, strings "aaaaa" , "1221" , "bbaabb" are palindromes, however the string "chef" is not a palindrome.

For cases where a sentence is given, spaces and case differences are ignored. For example, the phrase "A base do teto desaba" is considered a palindrome. When you read it from right to left, you get: "abased otet od esab A" . Notice that, with the exception of space, the string is the same as the original phrase.

How to write a program that indicates whether a given string is a palindrome or not using strings knowledge?

    
asked by anonymous 28.03.2016 / 21:53

3 answers

7

I was able to resolve it as follows:

string = raw_input()
stringSemEspacos = string.replace(' ', '')
stringTodaMinuscula = stringSemEspacos.lower()
stringInvertida = stringTodaMinuscula[::-1]
if stringInvertida == stringTodaMinuscula:
    print "SIM"
else:
    print "NAO"

After the string is supplied by the user, the spaces are replaced by a null using replace() (if the string is a phrase), assigning this new string to another variable stringSemEspacos . If the string is case-sensitive, the lower() function converts stringSemEspacos to stringTodaMinuscula , which has only lowercase letters. Subsequently, the string is inverted ( stringTodaMinuscula[::-1] ), and compared to stringSemEspaços . The comparison tests whether stringSemEspaços and stringInvertida (inverted string) are the same. Being equal, the given initial string checks for a palindrome.

    
28.03.2016 / 23:27
-2

To know whether the word is palindrome or not, using function. Explanation of some commands: ".lower ()" - > Returns the whole word with lowercase letters. "[:: - 1]" - > returns the word from back to front. "end = ''" - > Make the answer stay the same as the announcement of the response, as if it were just to continue on the same line.

def result(palavra):
    palavra_min = palavra.lower()
    palavra_invertida = palavra_min[::-1]
    if palavra_min == palavra_invertida:
        print("A palavra é palíndroma.")
    else:
        print("A palavra não é palíndroma.")
    print()
    print('Sua palavra: ', end='')
    print(palavra)
    print('Inversão: ', end='')
    print(palavra_invertida)


word=input('Digite uma palavra: ')
print(result(word))

                                                                   #Pedreiro
    
20.03.2017 / 02:53
-3

To decide whether or not the word is palindrome

f=input('Digite uma frase:  ')
if f==f[::-1]:
    print('A frase é palíndromo --> %s'%(f))
else:
    print('A frase não é palíndromo --> %s'%(f))
    
15.02.2017 / 02:34