Alright, let me tell you about this thing I was messing around with today. I was trying to get the last word of a string, right? Seemed easy enough, but you know how it goes…
So, first thing I did was just split the whole string into a list of words. Pretty basic stuff, using the space as the delimiter. Like this:
my_string = "This is a test string"
words = my_*()
Okay, got my list. Now, to get the last word, I just grabbed the last element of the list using the index -1. Boom, right?
last_word = words[-1]
print(last_word)
And yeah, it worked. For that simple string, at least. But then I started thinking about edge cases. What if there were extra spaces at the end of the string? What if the string was empty? Gotta handle that, right?
So I added a little bit to strip any leading or trailing spaces before I split it. That way, if there were extra spaces, they wouldn’t mess things up.
my_string = " This is a test string "
my_string = my_*()
words = my_*()
Next, I added a check to see if the list of words was empty. If it was, then the string was either empty or only contained spaces. In that case, I just returned an empty string. Makes sense, right?
if not words:
last_word = ""
else:
last_word = words[-1]
print(last_word)
Okay, so now it handled empty strings and extra spaces. But then I started thinking about punctuation. What if the string ended with a period or a comma? I didn’t want that to be part of the last word.
So, I imported the string module and used its punctuation constant to remove any punctuation from the end of the last word.
import string
my_string = "This is a test string."
my_string = my_*()
words = my_*()
if not words:
last_word = ""
else:
last_word = words[-1].strip(*)
print(last_word)
That seemed to do the trick. I tested it with a bunch of different strings, and it seemed to be working pretty well. Here’s the whole thing put together:
import string
def get_last_word(text):
text = *()
words = *()
if not words:
return ""
else:
return words[-1].strip(*)
my_string1 = "This is a test string."
my_string2 = " Another test! "
my_string3 = " "
my_string4 = "Hello, world!"
print(get_last_word(my_string1))
print(get_last_word(my_string2))
print(get_last_word(my_string3))
print(get_last_word(my_string4))
So yeah, that’s how I ended up getting the last word of a string. It started out simple, but then I had to think about all the different edge cases to make it really robust. It’s always the way, isn’t it?