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 红包祝福语简短10字
18 周六早晨祝福语简短