To check if a string contains a substring in Python, you can use the in
keyword or the str.find()
method. Here's how to do it with both methods, along with examples:
- Using the
in
keyword:
python
# Define the main string
main_string = "Hello, World!"
# Define the substring you want to check for
substring = "World"
# Check if the substring is present in the main string
if substring in main_string:
print(f"'{main_string}' contains the substring '{substring}'.")
else:
print(f"'{main_string}' does not contain the substring '{substring}'.")
Output:
sql
'Hello, World!' contains the substring 'World'.
- Using the
str.find()
method:
python
# Define the main string
main_string = "Hello, World!"
# Define the substring you want to check for
substring = "World"
# Check if the substring is present in the main string using str.find()
if main_string.find(substring) != -1:
print(f"'{main_string}' contains the substring '{substring}'.")
else:
print(f"'{main_string}' does not contain the substring '{substring}'.")
Output (same as above):
sql
'Hello, World!' contains the substring 'World'.
Both of these methods will allow you to check if a string contains a substring in Python.
Comments
Post a Comment