Python Tutorial
Python Flow Control
Python Functions
Python Data Types
Python Date and Time
Python Files
Python String
Python List
Python Dictionary
Python Variable
Python Input/Output
Python Exceptions
Python Advanced
To find a substring in a string in Python, you can use the in
keyword or the str.find()
method.
Here's an example using the in
keyword:
# The input string and substring input_string = "Hello, how are you?" substring = "how" # Check if the substring is in the input string if substring in input_string: print(f"The substring '{substring}' is in the input string.") else: print(f"The substring '{substring}' is not in the input string.")
Output:
The substring 'how' is in the input string.
Here's an example using the str.find()
method:
# The input string and substring input_string = "Hello, how are you?" substring = "how" # Find the first occurrence of the substring in the input string index = input_string.find(substring) # Check if the substring was found if index != -1: print(f"The substring '{substring}' is found at index {index}.") else: print(f"The substring '{substring}' is not in the input string.")
Output:
The substring 'how' is found at index 7.
In the first example, we use the in
keyword to check if the substring
is present in the input_string
. The result is a boolean value that indicates whether the substring is found (True
) or not (False
).
In the second example, we use the str.find()
method, which returns the index of the first occurrence of the substring in the input string. If the substring is not found, the method returns -1. This approach also provides the starting position of the substring in the input string, if found.
Python find substring in string:
my_string = "Hello, World!" substring = "World" if substring in my_string: print("Substring found!")
Finding substring index in Python:
my_string = "Hello, World!" substring = "World" index = my_string.find(substring) if index != -1: print(f"Substring found at index {index}")
Using str.index() to find substring in Python:
my_string = "Hello, World!" substring = "World" try: index = my_string.index(substring) print(f"Substring found at index {index}") except ValueError: print("Substring not found.")
Find all occurrences of substring in a string in Python:
my_string = "Hello, World! World is amazing. World" substring = "World" occurrences = [index for index in range(len(my_string)) if my_string.startswith(substring, index)] print(f"Substring found at indices: {occurrences}")
Count occurrences of substring in a string in Python:
my_string = "Hello, World! World is amazing. World" substring = "World" count = my_string.count(substring) print(f"Substring found {count} times.")
Find substring and replace in Python:
my_string = "Hello, World! World is amazing. World" substring = "World" replacement = "Universe" new_string = my_string.replace(substring, replacement) print(new_string)
Substring matching with regular expressions in Python:
import re my_string = "Hello, World! World is amazing. World" substring = "World" matches = re.finditer(substring, my_string) indices = [match.start() for match in matches] print(f"Substring found at indices: {indices}")
Python string slicing for substring extraction:
my_string = "Hello, World!" start_index = my_string.find("World") end_index = start_index + len("World") substring = my_string[start_index:end_index] print(substring)
Check if string starts with a substring in Python:
my_string = "Hello, World!" substring = "Hello" if my_string.startswith(substring): print("String starts with the substring.")
Case-insensitive substring search in Python:
my_string = "Hello, World!" substring = "world" if substring.lower() in my_string.lower(): print("Case-insensitive substring found!")
Finding multiple substrings in a string in Python:
my_string = "Hello, World! Python is awesome." substrings = ["Hello", "Python"] found_substrings = [sub for sub in substrings if sub in my_string] print(f"Found substrings: {found_substrings}")
Check if string ends with a substring in Python:
my_string = "Hello, World!" substring = "World!" if my_string.endswith(substring): print("String ends with the substring.")
Substring existence check with any() in Python:
my_string = "Hello, World!" substrings = ["Hello", "Python"] if any(sub in my_string for sub in substrings): print("At least one substring found!")
Substring search and count using collections.Counter in Python:
from collections import Counter my_string = "Hello, World! World is amazing. World" substrings = ["Hello", "World"] counts = Counter(my_string[start:end] for start, end in [(my_string.find(sub), my_string.find(sub) + len(sub)) for sub in substrings]) print(counts)