杰瑞科技汇

Python if in string 如何判断子串存在?

Of course! The most common and Pythonic way to check if a substring exists within a string is by using the in keyword.

Python if in string 如何判断子串存在?-图1
(图片来源网络,侵删)

Let's break it down with clear examples, from the basics to more advanced use cases.

The Basic in Keyword

The in operator returns True if a specified substring is found in a string, and False otherwise. It's case-sensitive.

Syntax:

if substring in main_string:
    # code to execute if substring is found
else:
    # code to execute if substring is NOT found

Example:

Python if in string 如何判断子串存在?-图2
(图片来源网络,侵删)
sentence = "The quick brown fox jumps over the lazy dog"
# Check if "fox" is in the sentence
if "fox" in sentence:
    print("Yes, the word 'fox' is in the sentence.")
else:
    print("No, the word 'fox' is not in the sentence.")
# Check if "cat" is in the sentence
if "cat" in sentence:
    print("Yes, the word 'cat' is in the sentence.")
else:
    print("No, the word 'cat' is not in the sentence.")
# --- Output ---
# Yes, the word 'fox' is in the sentence.
# No, the word 'cat' is not in the sentence.

Case-Sensitivity:

Notice that "Fox" (with a capital 'F') is not the same as "fox".

sentence = "The quick brown fox jumps over the lazy dog"
if "Fox" in sentence:
    print("Found 'Fox'") # This will not print
else:
    print("Did not find 'Fox'") # This will print
# --- Output ---
# Did not find 'Fox'

The not in Keyword

To check if a substring is NOT present, you can use not in.

Syntax:

Python if in string 如何判断子串存在?-图3
(图片来源网络,侵删)
if substring not in main_string:
    # code to execute if substring is NOT found
else:
    # code to execute if substring IS found

Example:

username = "john_doe_2025"
if "admin" not in username:
    print("Username is safe, it does not contain 'admin'.")
else:
    print("Warning: Username contains 'admin'!")
# --- Output ---
# Username is safe, it does not contain 'admin'.

Case-Insensitive Checks

What if you want to perform a check that ignores case? You have a couple of excellent options.

Option A: Convert to Lowercase (Recommended)

This is the most common and readable approach. Convert both strings to the same case (e.g., lowercase) before checking.

sentence = "The quick brown Fox jumps over the lazy dog"
# Convert both to lowercase for the comparison
if "fox" in sentence.lower():
    print("Found 'fox' (case-insensitive check).")
else:
    print("Did not find 'fox'.")
# --- Output ---
# Found 'fox' (case-insensitive check).

Option B: Use str.casefold()

casefold() is similar to lower() but is more aggressive in removing case distinctions. It's the recommended method for caseless matching, especially for non-English characters.

sentence = "The quick brown Fox jumps over the lazy dog"
if "fox" in sentence.casefold():
    print("Found 'fox' (using casefold).")
else:
    print("Did not find 'fox'.")
# --- Output ---
# Found 'fox' (using casefold).

Checking for a Full Word vs. a Substring

A common point of confusion is the difference between checking for a substring and checking for a whole word.

  • in checks for a substring. It will find "cat" inside "caterpillar".
  • To check for a whole word, you need to be more careful. A simple approach is to check for the word with spaces around it.

Example (Whole Word Check):

text = "I have a cat and a caterpillar."
# Check for the whole word "cat"
if " cat " in text:
    print("Found the whole word 'cat'.")
else:
    print("Did not find the whole word 'cat'.")
# Check for the substring "cat"
if "cat" in text:
    print("Found the substring 'cat'.")
# --- Output ---
# Found the whole word 'cat'.
# Found the substring 'cat'.

A More Robust Whole-Word Check:

The space method fails if the word is at the beginning or end of the string. A more robust way is to split the string into a list of words and check if the word is in that list.

text = "The cat is good."
# Check for the whole word "cat"
words = text.split()
if "cat" in words:
    print("Found the whole word 'cat' using split().")
else:
    print("Did not find the whole word 'cat' using split().")
# --- Output ---
# Found the whole word 'cat' using split().

Alternative Methods (For Specific Cases)

While in is the best for simple existence checks, other methods can be useful.

str.find()

Returns the lowest index of the substring if found, otherwise returns -1. It's useful when you also need the position.

sentence = "Hello world"
# Find the index of "world"
index = sentence.find("world")
if index != -1:
    print(f"Found 'world' at index: {index}")
else:
    print("Did not find 'world'.")
# --- Output ---
# Found 'world' at index: 6

str.index()

This is similar to find(), but it raises a ValueError if the substring is not found. Use this if you expect the substring to be there and an error is a better way to handle a "not found" situation.

try:
    index = "Hello world".index("python")
    print(f"Found 'python' at index: {index}")
except ValueError:
    print("Did not find 'python', as expected.")
# --- Output ---
# Did not find 'python', as expected.

Summary: Which Method to Use?

Method What it Does When to Use It
in Returns True or False. This is your default choice. Use it for simple, readable checks if a substring exists.
not in Returns True or False. Use it for simple, readable checks if a substring does not exist.
.lower() / .casefold() Returns a new string in lower case. Use with in for case-insensitive checks.
.split() Returns a list of words. Use when you need to check for a whole word (not a substring).
.find() Returns the index or -1. Use when you need to know the position of the substring.
.index() Returns the index or raises an error. Use when you expect the substring to be there and want to handle its absence as an error.
分享:
扫描分享到社交APP
上一篇
下一篇