
Data Structure
Networking
RDBMS
Operating System
Java
MS Excel
iOS
HTML
CSS
Android
Python
C Programming
C++
C#
MongoDB
MySQL
Javascript
PHP
- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who
Test for Desired String Lengths in Python
When it is required to test for desired string lengths, a simple iteration, and the ‘len’ method is used.
Example
Below is a demonstration of the same −
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")
Output
The list is : ['python', 'is', 'fun', 'to', 'learn', 'Will', 'how'] The result is : All the strings are of required lengths
Explanation
A list of strings is defined and is displayed on the console.
A list of integers is also defined.
A Boolean value is set to ‘True’.
The string list is iterated over, and if the respective index’s length is not equal to the value in the integer list’s same index, the Boolean value is set to False.
The control breaks out of the loop.
Depending on the Boolean value, relevant message is displayed on the console.
Advertisements