Python - 测试所需的字符串长度
当需要测试所需的字符串长度时,使用简单的迭代和'len'方法。
示例
以下是相同的演示-
my_list = ["python", 'is', 'fun', 'to', 'learn', 'Will', 'how']
print("名单是:")
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("结果是:")
if(my_result == True):
print("All the strings are of required lengths")
else:
print("All the strings are not of required lengths")输出结果名单是: ['python', 'is', 'fun', 'to', 'learn', 'Will', 'how'] 结果是: All the strings are of required lengths
解释
定义了一个字符串列表并显示在控制台上。
还定义了一个整数列表。
布尔值设置为“真”。
遍历字符串列表,如果相应索引的长度不等于整数列表的同一索引中的值,则布尔值设置为False。
控制跳出循环。
根据布尔值,控制台上会显示相关消息。