Welcome to collectivesolver - Programming & Software Q&A with code examples. A website with trusted programming answers. All programs are tested and work.

Contact: aviboots(AT)netvision.net.il

Semrush - keyword research tool

Create your online store today with Shopify

Turn ChatGPT, Claude, Gemini, And CoPilot Into Your Personal Assistant, Business Coach, Content Creator, And More

AFFILIATE MARKETING Your all-in-one performance engine Manage affiliates, creators, and customer referrals in one unified platform—turning every partnership into measurable growth
Secure & Reliable Web Hosting, Free Domain, Free SSL, 1-Click WordPress Install, Expert 24/7 Support

Disclosure: My content contains affiliate links.

43,038 questions

55,895 answers

573 users

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
...