Python Get the Last Word of a String
In Python, we can use the string's split() method splits a string into a list of words, then gets 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
)
(
last_word
)
Code analysis:
text.split(): Split the stringtextinto a list of words by spaceswords。words[-1]: Get the last element of the listwords, which is the last word.if words else "": IfwordsIf the list is empty (i.e., the string is empty), return an empty string.
Output result:
string
Python3 Examples