Python - 測試所需字串長度
當需要測試所需的字串長度時,使用簡單迭代和長度方法。
示例
以下演示了同樣的程式碼:
my_list = ["python", 'is', 'fun', 'to', 'learn', 'Will', 'how'] print("The list is :") print(my_list) length_list = [6, 2, 3, 2, 5, 4, 3] my_result = True for index in range(len(my_list)): if len(my_list[index]) != length_list[index]: my_result = False break print("The result is :") if(my_result == True): print("All the strings are of required lengths") else: print("All the strings are not of required lengths")
輸出
The list is : ['python', 'is', 'fun', 'to', 'learn', 'Will', 'how'] The result is : All the strings are of required lengths
解釋
定義了一個字串列表,並在控制檯上顯示。
還定義了一個整數列表。
布林值設定為“True”。
對字串列表進行迭代,如果相應索引的長度不等於整數列表中相同索引中的值,則將布林值設定為 False。
控制從迴圈中退出。
根據布林值,在控制檯上顯示相關訊息。
廣告