TUTORIALProgrammingFETCHED
Python 获取字符串的最后一个单词
Python 获取字符串的最后一个单词 Python3 实例 在 Python 中,我们可以使用字符串的 split() 方法将字符串分割成单词列表,然后通过索引获取最后一个单词。 实例 [mycode4 type='python'] def get_last_word(text): words = text.split() return words[-1] if words else �..
Updated 7/16/2026
Tutorial detail pages default to noindex.
Python 获取字符串的最后一个单词
在 Python 中,我们可以使用字符串的 split() 方法将字符串分割成单词列表,然后通过索引获取最后一个单词。
实例
def get_last_word(text):
words = text.split()
return words[-1] if words else ""
# 示例
text = "Hello, this is a test string"
last_word = get_last_word(text)
print(last_word)
words = text.split()
return words[-1] if words else ""
# 示例
text = "Hello, this is a test string"
last_word = get_last_word(text)
print(last_word)
代码解析:
text.split():将字符串text按空格分割成一个单词列表words。words[-1]:获取列表words中的最后一个元素,即最后一个单词。if words else "":如果words列表为空(即字符串为空),则返回空字符串。
输出结果:
string
Python3 实例