Python で文字列の最後の単語を取得する
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)
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)
コード解析:
text.split(): 文字列をtextスペースで単語リストに分割しますwords。words[-1]: リストのwords最後の要素、つまり最後の単語を取得します。if words else "": もしwordsリストが空(つまり文字列が空)の場合、空の文字列を返します。
出力結果:
stringその他の拡張
Python3 例