Python - 查找字符串中最后一个单词的长度
pythonserver side programmingprogramming更新于 2025/11/8 9:16:17
当需要查找字符串中最后一个单词的长度时,会定义一个方法,该方法会删除字符串中多余的空格,并遍历字符串。它会一直迭代直到找到最后一个单词。然后,找到其长度并将其作为输出返回。
示例
下面是相同的演示
def last_word_length(my_string):
init_val = 0
processed_str = my_string.strip()
for i in range(len(processed_str)):
if processed_str[i] == " ":
init_val = 0
else:
init_val += 1
return init_val
my_input = "Hi how are you Will"
print("The string is :")
print(my_input)
print("The length of the last word is :")
print(last_word_length(my_input))
输出
The string is : Hi how are you Will The length of the last word is : 4
解释
定义了一个名为‘last_word_length’的方法,该方法以字符串为参数。
它将值初始化为 0。
字符串被删除多余的空格,并进行迭代。
当遇到空格时,值保持为 0,否则加 1。
在方法之外,定义了一个字符串并显示在控制台上。
通过传递此字符串作为参数来调用该方法。
输出显示在控制台上。
相关文章
有用资源
python 参考教程 - 该教程包含有关 python 的更多信息:https://www.cainiaomax.com/python/

