Python - 测试所需字符串长度
当需要测试所需的字符串长度时,使用简单迭代和长度方法。
示例
以下演示了同样的代码:
my_list = ["python", 'is', 'fun', 'to', 'learn', 'Will', 'how']
print("The list is :")
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("The result is :")
if(my_result == True):
print("All the strings are of required lengths")
else:
print("All the strings are not of required lengths")输出
The list is : ['python', 'is', 'fun', 'to', 'learn', 'Will', 'how'] The result is : All the strings are of required lengths
解释
定义了一个字符串列表,并在控制台上显示。
还定义了一个整数列表。
布尔值设置为“True”。
对字符串列表进行迭代,如果相应索引的长度不等于整数列表中相同索引中的值,则将布尔值设置为 False。
控制从循环中退出。
根据布尔值,在控制台上显示相关消息。
广告
数据结构
网络
RDBMS
操作系统
Java
iOS
HTML
CSS
Android
Python
C 编程
C++
C#
MongoDB
MySQL
Javascript
PHP