如何检查单词是否是回文(Python)

时间:2016-11-05 12:41:33

标签: python

请帮忙...... 因此,指令说要对计算机进行编程,以检查单词是否是回文。我输入了这段代码:

def is_palindrome(word):

counter_from_first_letter=0
counter_from_last_letter=-1

from_first_letter = word[counter_from_first_letter]
from_last_letter = word[counter_from_last_letter]

max_index_from_first= len(word)
max_index_from_last= (len(word))*-1

while from_first_letter == from_last_letter:  
    from_first_letter = word[counter_from_first_letter]
    from_last_letter = word[counter_from_last_letter]

    counter_from_first_letter += 1
    counter_from_last_letter -= 1
    return True

问题是计算机只检查第一个和最后一个字母是否相同,如果是,则只返回true。如何确保计算机检查每一个字母?感谢

4 个答案:

答案 0 :(得分:0)

也许是这样的:

def is_palindrome(word):
    if word == word[::-1]:
        return True
    else:
        return False

答案 1 :(得分:0)

也许您可以尝试这样做:首先将您的字符串转换为列表,然后反转列表并将其转换回字符串。比较两个字符串,如果匹配?他们是回文,如果没有,他们就不是。

'''checking whether a word is a palindrome
we first convert the word into a list then join it;
use an if statement to compare the two strings'''

def palindrome(string):#you need the input(string)
    palindrome_check=[]#create an empty list
    for character in string [::-1]:#create a list from the input
        #(use a for loop because you now know the range)
        #the [::-1] analyzes the characters in reverse 
        palindrome_check.append(character)#add each character to the new empty list
    #print(palindrome_check)
    rev_string= ''.join(palindrome_check)#.join -creates a string from the created list
    print(rev_string)
    #REMOVE SPECIAL CHARACTERS- IM THINKING OF A LOOPING THROUGH, BUT NOT SURE HOW TO IMPLEMENT IT
    string=string.replace(' ', '')
    rev_string=rev_string.replace(' ', '')
    string=string.replace(',', '')
    rev_string=rev_string.replace(',', '')
    string=string.replace('.', '')
    rev_string=rev_string.replace('.', '')
    #THIS IS THE LOGIC: IT CHECKS BOTH STRINGS, if they are equal, it is a palindrome; 
    if string.lower()==rev_string.lower():
        return True, print('It is a Palindrome')
    else:
        return False, print('It isnt a palindrome')

#call the function; key in the parameters- 
palindrome= palindrome("No, Mel Gibson Is A Casinos Big Lemon")
#maybe we can try having a user key in the parameter? lets try
#palindrome=palindrome(input('kindly enter your word/phrase  '))-wrong
#print('Kindly enter your word or phrase')
#user_palindrome=input('')
#palindrome=palindrome(user_palindrome)
#it wont work this way either

如果你可以让用户定义参数(字符串),那么如果你知道怎么做就更好,请分享。

答案 2 :(得分:0)

要检查单词或短语是否是回文,有必要检查原始句子是否等于反转的原始句子。

word = "Eva can I see bees in a cave"

word_lower = word.lower().replace(" ", "")

if word_lower == word_lower[::-1]:
    print("It's a palindrome")
else:
    print("This is not a palindrome")

答案 3 :(得分:0)

在python-3

name = 'madam'
print(name.find(name[::-1]) == 0)