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。

  • 在方法外部,定義一個字串並在控制檯上顯示。

  • 透過將此字串作為引數呼叫該方法。

  • 輸出顯示在控制檯上。

更新於: 2021年9月20日

2K+ 次瀏覽

開啟您的 職業生涯

透過完成課程獲得認證

立即開始
廣告

© . All rights reserved.