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。
控制跳出循环。
根据布尔值,控制台上会显示相关消息。
热门推荐
1 训练狗狗憋尿
2 狗狗追踪训练
3 狗狗训练要多少钱
5 深圳狗狗训练
6 训练狗狗唤回
7 狗狗叫怎么训练
8 狗狗训练班
10 狗狗社会化训练
11 狗狗叫回训练
12 广州狗狗训练学校
13 狗狗训练躺下
14 狗狗随行训练
15 训练狗狗巡回
16 狗狗要怎么训练
17 狗狗喂食训练
18 训练狗狗躺下