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。
控制跳出循环。
根据布尔值,控制台上会显示相关消息。
热门推荐
10 香港老妈结婚祝福语简短
11 毕业立体贺卡祝福语简短
12 简短新年年会祝福语
13 评论小品祝福语大全简短
14 恭喜师兄结婚祝福语简短
15 员工集体辞职祝福语简短
16 高中新生祝福语 简短
17 装修祝福语男生搞笑简短
18 生日开业蛋糕祝福语简短