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.