Private archive copy · Unofficial site · Content copyright belongs to Runoob Tutorial and the original authors · View Original

Python Get the Last Word of a String

Python Get the Last Word of a String

Document Object Reference Manual Python3 Examples

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

)

print

(

last_word

)

Code analysis:

  1. text.split(): Split the string text into a list of words by spaces words。
  2. words[-1]: Get the last element of the list words , which is the last word.
  3. if words else "": If words If the list is empty (i.e., the string is empty), return an empty string.

Output result:

string

Document Object Reference Manual Python3 Examples