简体   繁体   English

如何检查一个字母是否等于一个字母python

[英]how to check if a letter equals an letter-python

so i have this code and the goal is to see if an word is an palindrome and is supposed to return true if the word is an palindrome and false if it isn't.所以我有这个代码,目标是看看一个词是否是回文,如果这个词是回文,应该返回真,如果不是,则返回假。 for now it always returns false.现在它总是返回false。

here is my code so far:到目前为止,这是我的代码:

# main.py
def pal(string):
  
  if len(string)==1 or len(string)==0:
    return True
    
  if string[1] == string[len(string)-1]:
    pal(string[1,-1])
  else:
    return False
print(pal("dad"))

please tell me how to fix it and not try to shorten it because I want to learn from my mistakes.请告诉我如何修复它而不是试图缩短它,因为我想从我的错误中吸取教训。

First of all, your check for "first character equals last character" should be首先,您对“第一个字符等于最后一个字符”的检查应该是

if string[0] == string[-1]:

Strings/lists/etc.字符串/列表/等。 are 0-indexed, meaning that the first element has index 0. In python, you can access the last element of a string/list by using the index -1 (or the second last with -2 , etc.), which counts backwards from the back of the array.是 0 索引的,这意味着第一个元素的索引为 0。在 Python 中,您可以使用索引-1 (或倒数第二个-2等)访问字符串/列表的最后一个元素,该索引向后计数从阵列的后面。 Other languages do require you to take the length of the string/list and subtract one, but in python string[len(string) - 1] and string[-1] are functionally identical.其他语言确实要求您取字符串/列表的长度并减去一,但在 python 中string[len(string) - 1]string[-1]在功能上是相同的。

Next, the syntax for "slicing" a string or list is : , not , :接下来,“切片”字符串或列表的语法是: , not , :

pal(string[1:-1])

And finally, you need to return this recursive call.最后,您需要返回这个递归调用。 Just calling the function without explicitly returning it won't do anything:只调用函数而不显式返回它不会做任何事情:

return pal(string[1:-1])

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM