Python で文字列の最後の単語を取得する

Document 对象参考手册Python3 例

Python では、文字列のsplit()メソッドを使用して文字列を単語のリストに分割し、インデックスで最後の単語を取得できます。

例

def get_last_word(text):
    words = text.split()
    return words[-1] if words else ""

# 例
text = "Hello, this is a test string"
last_word = get_last_word(text)
print(last_word)

コード解析:

  1. text.split(): 文字列をtextスペースで単語リストに分割しますwords。
  2. words[-1]: リストのwords最後の要素、つまり最後の単語を取得します。
  3. if words else "": もしwordsリストが空(つまり文字列が空)の場合、空の文字列を返します。

出力結果:

string

Document 对象参考手册Python3 例

その他の拡張