1

文字列が関係する Python の問題で少し困っています。

プロンプトは次のとおりです。

文字列の最初の文字が文字列の最後の文字と同じ場合、異なる場合はfirst_and_last返すように関数を変更します。またはを使用して文字にアクセスできることに注意してください。空の文字列の処理方法に注意してください。何も等しいものはないため、返される必要があります。TrueFalsemessage[0]message[-1]True

これは私が持っているものです:

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(""))

そして、私が受け取っている出力:

True
True
None

完全でfirst_and_last("tree")Trueありません False。空の文字列のチェックを追加し、正しい文字列インデックスを使用しましたか? ヒント: Python での文字列処理において、0 と -1 のインデックス番号は何を意味しますか?

誰でも助ける方法を知っていますか?

4

5 に答える 5

0

「not」および「or」比較演算子を使用して、目的の結果を出力できます。

def first_and_last(message):
    if not message or message[0] == message[-1]:
        return True
    else:
        return False
于 2020-04-01T04:18:04.807 に答える