How to get the last word from a string in Python

2 Answers

0 votes
s = "python java c++ c c# php"
 
word = s.split()[-1]
 
print(word)
 
 
 
 
'''
run:
 
php
  
'''

 



answered Jul 30, 2020 by avibootz
0 votes
def get_last_word(text: str) -> str:
    """
    Return the last word in a string.
    Empty or whitespace-only strings return an empty string.
    """
    # Strip leading/trailing whitespace
    stripped = text.strip()

    # If nothing remains, return empty string
    if not stripped:
        return ""

    # Split into words and return the last one
    return stripped.split()[-1]


# Test cases
tests = [
    "vb.net javascript php c c++ python c#",
    "",
    "c#",
    "c c++ java ",
    "  "
]

for i, t in enumerate(tests, start=1):
    print(f"{i}. {get_last_word(t)}")


"""
run:

1. c#
2. 
3. c#
4. java
5.

"""

 



answered Mar 27 by avibootz
...