Python – 查詢長度大於指定長度的單詞


當需要查詢長度大於特定長度的單詞時,可以定義一個方法來分割字串並迭代它。該方法檢查單詞的長度並將其與給定長度進行比較。如果匹配,則將其作為輸出返回。

示例

以下是相同的演示

def string_check(string_length, my_string):
   result_string = []
   words = my_string.split(" ")
   for x in words:
      if len(x) > string_length:
         result_string.append(x)
   return result_string
string_length = 3
my_string ="Python is always fun to learn"

print("The string is :")
print(my_string)
print "\nThe words in the string with length greater than" , string_length , "is :"
print(string_check(string_length, my_string))

輸出

The string is :
Python is always fun to learn

The words in the string with length greater than 3 is :
['Python', 'always', 'learn']

解釋

  • 定義了一個名為“string_check”的方法,該方法將字串及其長度作為引數。

  • 定義一個空列表。

  • 根據空格分割字串,並將其賦值給一個變數。

  • 迭代此變數,並檢查給定長度和每個單詞的長度。

  • 如果單詞的長度大於字串的長度,則將其新增到空字串中。

  • 將其作為輸出返回。

  • 在函式外部,定義字串長度和字串。

  • 此字串將顯示在控制檯上。

  • 呼叫該方法並在控制檯上顯示輸出。

更新於:2021年9月20日

1K+ 次瀏覽

開啟你的職業生涯

完成課程獲得認證

開始學習
廣告
© . All rights reserved.