Coursera: Parts of a String

cesaire talom picture cesaire talom · Mar 22, 2020 · Viewed 11.2k times · Source

I'm having a bit of trouble with a Python problem that involves strings.

The prompt is:

Modify the first_and_last function so that it returns True if the first letter of the string is the same as the last letter of the string, False if they’re different. Remember that you can access characters using message[0] or message[-1]. Be careful how you handle the empty string, which should return True since nothing is equal to nothing.

This is what I have:

def first_and_last(message):
  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?

Answer

dtc picture dtc · Mar 22, 2020

I'll avoid answering the problem itself and try to give some hints to guide you:

  • "What do the index numbers of 0 and -1 mean for string handling in Python?" - well, this was already given to you.
  • What is the difference between char and message? What types of objects are both of those? In fact, char[0] and char[-1] seems odd. Shouldn't that cause an exception?
  • Programming languages, especially ones like python, are a playground. Printing objects usually helps you understand what's going on. (Try printing each char in the message and see what you get)