Article Categories
- All Categories
-
Data Structure
-
Networking
-
RDBMS
-
Operating System
-
Java
-
MS Excel
-
iOS
-
HTML
-
CSS
-
Android
-
Python
-
C Programming
-
C++
-
C#
-
MongoDB
-
MySQL
-
Javascript
-
PHP
-
Economics & Finance
Selected Reading
Python program to find the String in a List
When it is required to find the string in a list, a simple 'if' condition along with 'in' operator can be used. Python provides several approaches to check if a string exists in a list.
Using the 'in' Operator
The most straightforward way is using the 'in' operator, which returns True if the string is found ?
my_list = [4, 3.0, 'python', 'is', 'fun']
print("The list is :")
print(my_list)
key = 'fun'
print("The key is :")
print(key)
print("The result is :")
if key in my_list:
print("The key is present in the list")
else:
print("The key is not present in the list")
The list is : [4, 3.0, 'python', 'is', 'fun'] The key is : fun The result is : The key is present in the list
Using count() Method
The count() method returns the number of occurrences of a string in the list ?
fruits = ['apple', 'banana', 'orange', 'apple', 'grape']
search_fruit = 'apple'
count = fruits.count(search_fruit)
print(f"'{search_fruit}' appears {count} times in the list")
if count > 0:
print(f"'{search_fruit}' is present in the list")
else:
print(f"'{search_fruit}' is not present in the list")
'apple' appears 2 times in the list 'apple' is present in the list
Using any() with List Comprehension
For partial string matching or more complex conditions, use any() with list comprehension ?
words = ['programming', 'python', 'coding', 'development']
substring = 'prog'
# Check if any word contains the substring
found = any(substring in word for word in words)
print(f"Words containing '{substring}': {found}")
# Find all words containing the substring
matching_words = [word for word in words if substring in word]
print(f"Matching words: {matching_words}")
Words containing 'prog': True Matching words: ['programming']
Comparison
| Method | Returns | Best For |
|---|---|---|
in operator |
True/False | Exact string matching |
count() |
Number of occurrences | Counting occurrences |
any() |
True/False | Partial matching or complex conditions |
Explanation
- A list of integers and strings is defined and displayed on the console.
- The 'in' operator checks for exact matches and returns a boolean value.
- The count() method is useful when you need to know how many times a string appears.
- List comprehension with any() provides flexibility for partial matching or custom conditions.
Conclusion
Use the 'in' operator for simple exact string matching. Use count() when you need occurrence frequency, and any() with list comprehension for partial matching or complex conditions.
Advertisements
