Python:字符串课程的一部分

问题描述 投票:0回答:1

我在涉及字符串的Python问题上有点麻烦。提示是:

修改first_and_last函数,如果字符串的第一个字母与字符串的最后一个字母相同,则返回True,否则返回False。请记住,您可以使用message [0]或message [-1]访问字符。请注意如何处理空字符串,该字符串应返回True,因为什么都不等于什么。

这是我所拥有的:

  for char in message:
    if char[0] == char[-1]:
      return True
    elif char == " ":
      return True
    else:
      return False

print(first_and_last("else"))
print(first_and_last("tree"))
print(first_and_last(""))```

And the output I'm receiving: 

```True
True
None

Not quite, first_and_last("tree") returned True, should be
False. Have you added the check for empty strings, and used
correct string indexing? Hint: what do the index numbers of
0 and -1 mean for string handling in Python?```

Anyone have any idea how to help?
python string coursera-api
1个回答
0
投票

“索引号0和-1对Python中的字符串处理意味着什么?” -好,这已经给你了。

    char和message有什么区别?这些都是什么类型的对象?实际上,char [0]和char [-1]似乎很奇怪。那不应该引起异常吗?
  • [编程语言,尤其是python之类的语言,是一个游乐场。打印对象通常可以帮助您了解发生了什么。 (尝试打印消息中的每个字符并查看得到的内容)
© www.soinside.com 2019 - 2024. All rights reserved.