Python - 查找字符串中最后一个单词的长度
当需要查找字符串中最后一个单词的长度时,定义一个方法来去除字符串中多余的空格,并遍历字符串。它会一直迭代直到找到最后一个单词。然后,找到它的长度并将其作为输出返回。
示例
下面是同一示例的演示
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。
在方法外部,定义一个字符串并在控制台上显示。
通过将此字符串作为参数调用该方法。
输出显示在控制台上。
广告
数据结构
网络
关系型数据库管理系统
操作系统
Java
iOS
HTML
CSS
Android
Python
C 编程
C++
C#
MongoDB
MySQL
Javascript
PHP