How to remove the last word from a string with Python

2 Answers

0 votes
s = "java c c++ java python java"

s = s[:s.rfind(" ")]

print(s)



'''
run:

java c c++ java python

'''

 



answered Sep 10, 2024 by avibootz
0 votes
def remove_last_word(s: str) -> str:
    # Trim trailing whitespace
    s = s.rstrip()

    # Find last space
    pos = s.rfind(" ")

    # If no space found, return original
    if pos == -1:
        return s

    return s[:pos]


def main():
    s = "c c++ c# java python"
    print("1.", remove_last_word(s))

    s = ""
    print("2.", remove_last_word(s))

    s = "c"
    print("3.", remove_last_word(s))

    s = "c# java python "
    print("4.", remove_last_word(s))

    s = "  "
    print("5.", remove_last_word(s))


if __name__ == "__main__":
    main()


'''
run:

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

'''

 



answered Mar 27 by avibootz
...