แยกสตริงเป็นคำ (split()) แล้วกรองคำที่มีความยาวเกินค่าที่กำหนด
ตัวอย่างโค้ด
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รับความยาวเกณฑ์และสตริง split(" ")แยกคำด้วยช่องว่าง- วนลูปเช็ค
len(x) > string_length - เก็บคำที่ผ่านเกณฑ์ไว้ในลิสต์ผลลัพธ์