Python Get the Last Word of a String

Document 对象参考手册Python3 Examples

In Python, we can use the string'ssplit()method to split the string into a list of words, then get the last word by index.

Example

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

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

Code explanation:

  1. text.split(): Split the stringtextinto a list of words by spaceswords。
  2. words[-1]: Get the listwordsThe last element in the list, i.e., the last word.
  3. if words else "": IfwordsIf the list is empty (i.e., the string is empty), return an empty string.

Output:

string

Document 对象参考手册Python3 Examples

Other Extensions