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 男生搬家花束祝福语简短