在Python中,我们可以使用split()函数将字符串拆分为单词列表。然后,我们可以使用列表索引-1来获取列表中的最后一个单词。
以下是一个示例代码:
def get_last_word(string):
words = string.split()
if len(words) > 0:
return words[-1]
else:
return None
# 测试示例
string1 = "Hello world"
print(get_last_word(string1)) # 输出: world
string2 = "I am not sure how to explain the last word in this string"
print(get_last_word(string2)) # 输出: string
string3 = ""
print(get_last_word(string3)) # 输出: None
在上面的示例中,函数get_last_word()
接收一个字符串作为参数。首先,我们使用split()函数将字符串拆分为单词列表。然后,我们检查列表的长度是否大于0,如果大于0,就返回列表中的最后一个单词。否则,返回None表示没有单词。
请注意,如果字符串为空字符串,则返回None。这是为了处理边缘情况,以防止在空字符串上尝试访问索引-1导致错误。