Python Get the Last Word of a String
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)
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:
text.split(): Split the stringtextinto a list of words by spaceswords。words[-1]: Get the listwordsThe last element in the list, i.e., the last word.if words else "": IfwordsIf the list is empty (i.e., the string is empty), return an empty string.
Output:
stringOther Extensions
Python3 Examples