我需要编写一个Python程序,只给我字符串中最后一个单词的长度。
但是,如果最后没有单词,它应该返回0。
例如
input = 'Hello World'
output = length of World = 5
input = "Hello World '
Output = 5
input = " "
output = 0
rsplit
按分隔符(空格)计数(1)次分割字符串。如果没有,rsplit
返回一个长度为零的字符串列表(只适用于分隔符)。没有分隔符,可能会得到空数组。更多信息见文档
因此,在通过索引访问之前不需要检查
返回最后一项的长度。
def last_word_length(string):
return len(string.rsplit(' ', 1)[-1])
测试:
print(last_word_length('Hello world')) # 5
print(last_word_length(' ')) # 0
print(last_word_length('')) # 0
print(last_word_length('a')) # 1