惯性聚合 高效追踪和阅读你感兴趣的博客、新闻、科技资讯
阅读原文 在惯性聚合中打开

推荐订阅源

宝玉的分享
宝玉的分享
H
Hackread – Cybersecurity News, Data Breaches, AI and More
让小产品的独立变现更简单 - ezindie.com
让小产品的独立变现更简单 - ezindie.com
小众软件
小众软件
月光博客
月光博客
D
DataBreaches.Net
L
LangChain Blog
美团技术团队
S
SegmentFault 最新的问题
MyScale Blog
MyScale Blog
大猫的无限游戏
大猫的无限游戏
博客园 - 司徒正美
aimingoo的专栏
aimingoo的专栏
奇客Solidot–传递最新科技情报
奇客Solidot–传递最新科技情报
H
Help Net Security
阮一峰的网络日志
阮一峰的网络日志
Y
Y Combinator Blog
I
InfoQ
U
Unit 42
Microsoft Azure Blog
Microsoft Azure Blog
J
Java Code Geeks
博客园 - 三生石上(FineUI控件)
腾讯CDC
Martin Fowler
Martin Fowler

DigitalOcean Community Tutorials

Mastering grep with Regular Expressions for Efficient Text Search It's Time to Break Up with Your Cloud: Why AI Teams are Switching We Built a Private-Document AI App to Test Platform Security. Here Is What We Could Actually Verify. PostgreSQL Explained: A Complete Beginner-to-Advanced Guide How To Install and Configure Postfix on Ubuntu How To Build a Web Application Using Flask in Python 3 Build AI Reading List with DigitalOcean Functions and Mistral How To Concatenate Strings in Python How to Allow MySQL Remote Access Securely How To Install and Use Docker on Rocky Linux How To Build a Multi-Agent AI System with Docker Agent DSPy Use Cases: Build Optimized LLM Pipelines How To Submit AJAX Forms with jQuery Build an AI-Powered GPU Fleet Optimizer with the DigitalOcean AI Platform ADK Monitor GPU Utilization in Real Time: A Complete Guide Reduce File Size of Images in Linux - CLI and GUI methods Reduce PDF File Size in Linux: Tools and Methods How To Set Up a Private Docker Registry on Ubuntu How To Troubleshoot Terraform: Errors and Fixes How to Use Go Modules Python Multiprocessing Example: Process, Pool & Queue Convert Class Components to Functional Components with React Hooks How To Install and Configure Ansible on Ubuntu LLM Tokenizers Simplified: BPE, SentencePiece, and More How To Monitor System Authentication Logs on Ubuntu How to Use Traceroute and MTR to Diagnose Network Issues How to Deploy Postgres to Kubernetes Cluster Importing Packages in Go: A Complete Guide Create RAID Arrays with mdadm on Ubuntu How To Make an HTTP Server in Go
How To Check If a String Contains Another String in Python
Pankaj Kumar · 2022-08-04 · via DigitalOcean Community Tutorials

Introduction

Checking if a string contains another substring is a common task when working with Python. String manipulation is a common task in any programming language. Python provides two common ways to check if a string contains another string.

Key Takeaways

  • The in operator is the most readable and idiomatic way to check if a substring exists in a string. It returns True or False directly.
  • find() returns the index of the first match, or -1 if not found. Use it when you need the position, not just a boolean result.
  • index() behaves like find() but raises a ValueError if the substring is absent. Use it only when you expect the substring to always be present.
  • re.search() is the right choice for case-insensitive checks, pattern matching, or when the substring contains special characters.
  • Use re.escape() when searching for user-provided input that may contain regex special characters like $, ., or *.
  • All four methods are case-sensitive by default except when re.IGNORECASE is passed to re.search().

Different methods to check if a string contains another string

1. Using the in operator

Python string supports in operator. So we can use it to check if a string is part of another string or not. The in operator syntax is:

sub in str

It returns True if “sub” string is part of “str”, otherwise it returns False. Let’s look at some examples of using in operator in Python.

str1 = 'I love Python Programming'

str2 = 'Python'

str3 = 'Java'

print(f'"{str1}" contains "{str2}" = {str2 in str1}')
print(f'"{str1}" contains "{str2.lower()}" = {str2.lower() in str1}')
print(f'"{str1}" contains "{str3}" = {str3 in str1}')

if str2 in str1:
    print(f'"{str1}" contains "{str2}"')
else:
    print(f'"{str1}" does not contain "{str2}"')

Output:

"I love Python Programming" contains "Python" = True
"I love Python Programming" contains "python" = False
"I love Python Programming" contains "Java" = False
"I love Python Programming" contains "Python"

python check if string contains another string using in operator

If you are not familiar with f-prefixed strings in Python, it’s a new way for string formatting introduced in Python 3.6. You can read more about it at f-strings in Python.

When we use in operator, internally it calls __contains__() function. We can use this function directly too, however it’s recommended to use in operator for readability purposes.

s = 'abc'

print('s contains a =', s.__contains__('a'))
print('s contains A =', s.__contains__('A'))
print('s contains X =', s.__contains__('X'))

Output:

s contains a = True
s contains A = False
s contains X = False

2. Using find() to check if a string contains another substring

We can also use string find() function to check if string contains a substring or not. This function returns the first index position where substring is found, else returns -1.

str1 = 'I love Python Programming'

str2 = 'Python'

str3 = 'Java'

index = str1.find(str2)
if index != -1:
    print(f'"{str1}" contains "{str2}"')
else:
    print(f'"{str1}" does not contain "{str2}"')

index = str1.find(str3)
if index != -1:
    print(f'"{str1}" contains "{str3}"')
else:
    print(f'"{str1}" does not contain "{str3}"')

Output:

"I love Python Programming" contains "Python"
"I love Python Programming" does not contain "Java"

python check if a string contains a substring

3. Using index() Method

The index() method is similar to find() but raises a ValueError if the substring is not found.

text = "Python programming is fun"
index = text.index("fun")
print(index)  # Output: 21

Use index() when you expect the substring always to be present and want an error if it’s missing.

Regular expressions offer a powerful way to perform advanced pattern matching in strings. They allow for complex searches and extractions of data, making them a valuable tool in many applications.

In the following example, we use the re.search() function to search for the string “python” within the text “Learning Python is fun!”. The re.IGNORECASE flag is used to make the search case-insensitive, ensuring that the function matches “python”, “Python”, “PYTHON”, or any other variation of the string.

import re
text = "Learning Python is fun!"
match = re.search(r"python", text, re.IGNORECASE)
print(bool(match))  # Output: True

Understanding Regex Flags:

Regular expression flags are used to modify the behavior of the search function. Here are some common flags and their effects:

  • re.IGNORECASE (re.I): This flag makes the search case-insensitive, allowing the function to match strings regardless of their case. For example, it would match “python”, “Python”, “PYTHON”, or any other variation of the string.
  • re.MULTILINE (re.M): This flag treats ^ and $ as the start and end of each line, not just the string. This is useful when working with multi-line strings and you want to match patterns at the start or end of each line.
  • re.DOTALL (re.S): This flag allows the . character to match newline characters. By default, . does not match newline characters, but with this flag, it does.

Example:

Here’s an example of how to use multiple flags together to compile a regular expression pattern. In this case, we’re using re.IGNORECASE and re.MULTILINE to create a pattern that matches the string “hello” at the start of each line, regardless of case.

pattern = re.compile(r"^hello", re.IGNORECASE | re.MULTILINE)

Using re.IGNORECASE allows case-insensitive searches, making it useful for handling user input or inconsistent casing. This is particularly important when working with user-generated content, where the case of the input may vary.

Handling Special Characters

When searching for substrings that include special characters, it’s crucial to handle them correctly to ensure accurate matching. Special characters in regular expressions have specific meanings, such as $ indicating the end of a string or . matching any character except a newline. If these characters are part of the substring you’re searching for, they need to be escaped to be treated as literal characters.

The re.escape() function is designed to escape all special characters in a string, making it suitable for use in regular expressions. This function is particularly useful when working with user input or dynamic data that may contain special characters.

Here’s an example of how to use re.escape() to search for a substring that includes special characters:

import re
text = "Price: $10.99"
pattern = re.escape("$10.99")  # Escaping the special character $
match = re.search(pattern, text)
print(bool(match))  # Output: True

In this example, the $ character in the substring $10.99 is a special character in regular expressions. Without escaping, it would be interpreted as the end of the string, leading to incorrect matching. By using re.escape(), the $ is treated as a literal character, ensuring that the search matches the intended substring correctly.

Comparison Table

Method Return Type Case Sensitivity Error Handling Use Case
in Boolean (True/False) Case-sensitive No errors Quick check for substring presence
find() Integer (index or -1) Case-sensitive Returns -1 if not found Finding position without exceptions
index() Integer (index) Case-sensitive Raises ValueError if not found Ensuring substring is present
re.search() Match object or None Can be case-insensitive (re.IGNORECASE) No errors Advanced pattern matching

FAQs

1. How to check if a string contains a substring in Python?

You can use the in operator, the find() method, or regular expressions to check if a string contains a substring in Python. The in operator returns True if the substring is found, while the find() method returns the index of the first occurrence of the substring, or -1 if it’s not found. Regular expressions offer more advanced pattern matching and can be used for complex substring checks.

text = "Learning Python is fun!"
substring = "Python"
if substring in text:
    print(f'"{text}" contains "{substring}"')
else:
    print(f'"{text}" does not contain "{substring}"')

2. What is the difference between in and find()?

The in operator checks if a substring is present in a string and returns a boolean value. The find() method returns the index of the first occurrence of the substring, or -1 if it’s not found.

text = "Learning Python is fun!"
substring = "Python"
if text.find(substring) != -1:
    print(f'"{text}" contains "{substring}"')
else:
    print(f'"{text}" does not contain "{substring}"')

3. How to perform a case-insensitive string check?

To perform a case-insensitive string check, you can use the re.IGNORECASE flag with regular expressions. This flag makes the search case-insensitive, allowing the function to match strings regardless of their case.

import re
text = "Learning Python is fun!"
match = re.search(r"python", text, re.IGNORECASE)
print(bool(match))  # Output: True

4. When should I use regular expressions for substring checks?

You should use regular expressions for substring checks when you need more advanced pattern matching, such as matching a substring at the start of each line, or when you need to handle special characters in the substring.

import re
text = "Learning Python is fun!"
match = re.search(r"^Learning", text)
print(bool(match))  # Output: True

5. How to handle special characters in substring checks?

To handle special characters in substring checks, you can use the re.escape() function to escape all special characters in a string, making it suitable for use in regular expressions. This function is particularly useful when working with user input or dynamic data that may contain special characters.

import re
text = "Price: $10.99"
pattern = re.escape("$10.99")  # Escaping the special character $
match = re.search(pattern, text)
print(bool(match))  # Output: True

Conclusion

In this tutorial, you covered four methods for checking if a string contains another string in Python: the in operator for simple boolean checks, find() for index-based lookups, index() for cases where the substring must be present, and re.search() for pattern matching and case-insensitive checks. You also saw how to handle special characters safely using re.escape().

For most use cases, in is the right default. Reach for re.search() when your requirements go beyond exact, case-sensitive matching.

To continue working with Python strings:

Still looking for an answer?

Creative CommonsThis work is licensed under a Creative Commons Attribution-NonCommercial- ShareAlike 4.0 International License.