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

推荐订阅源

The Last Watchdog
The Last Watchdog
freeCodeCamp Programming Tutorials: Python, JavaScript, Git & More
GbyAI
GbyAI
Y
Y Combinator Blog
CTFtime.org: upcoming CTF events
CTFtime.org: upcoming CTF events
The GitHub Blog
The GitHub Blog
博客园_首页
小众软件
小众软件
I
InfoQ
J
Java Code Geeks
月光博客
月光博客
S
Secure Thoughts
Microsoft Security Blog
Microsoft Security Blog
V
Visual Studio Blog
Hacker News - Newest:
Hacker News - Newest: "LLM"
钛媒体:引领未来商业与生活新知
钛媒体:引领未来商业与生活新知
Stack Overflow Blog
Stack Overflow Blog
cs.CV updates on arXiv.org
cs.CV updates on arXiv.org
N
News and Events Feed by Topic
Exploit-DB.com RSS Feed
Exploit-DB.com RSS Feed
Threat Intelligence Blog | Flashpoint
Threat Intelligence Blog | Flashpoint
The Cloudflare Blog
T
Threat Research - Cisco Blogs
A
About on SuperTechFans
H
Help Net Security
MongoDB | Blog
MongoDB | Blog
博客园 - 聂微东
人人都是产品经理
人人都是产品经理
H
Hackread – Cybersecurity News, Data Breaches, AI and More
Recent Commits to openclaw:main
Recent Commits to openclaw:main
Latest news
Latest news
G
GRAHAM CLULEY
IT之家
IT之家
C
Cisco Blogs
Last Week in AI
Last Week in AI
Engineering at Meta
Engineering at Meta
L
LangChain Blog
The Register - Security
The Register - Security
SecWiki News
SecWiki News
M
MIT News - Artificial intelligence
NISL@THU
NISL@THU
T
Tenable Blog
博客园 - Franky
美团技术团队
I
Intezer
U
Unit 42
雷峰网
雷峰网
cs.AI updates on arXiv.org
cs.AI updates on arXiv.org
S
SegmentFault 最新的问题
C
Cyber Attacks, Cyber Crime and Cyber Security

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 Set Up Time Synchronization on Ubuntu How To Use Struct Tags in Go apt-key Deprecation: Add Repositories with GPG on Ubuntu Linux ps Command: 20 Real-World Examples Python struct.pack and struct.unpack for Binary Data Deadlock in Java: Examples, Detection, and Prevention How To Use Find and Locate to Search for Files on Linux Structured Resume Skill Extraction Using Mistral-7B Inference How to Use the Python Main Function How to Set Up NemoClaw on a DigitalOcean Droplet with 1-Click Build an End-to-End RAG Pipeline for LLM Applications From Single to Multi-Agent Systems: Key Infrastructure Needs Back Up Data to Object Storage Using Restic How to Generate Videos with LTX-2.3 on DigitalOcean GPU Droplets How To Install LAMP Stack (Apache, MySQL, PHP) on Ubuntu How to Download Files with cURL How To Use Variadic Functions in Go Generate UUIDs with uuidgen on Linux How To Use EJS to Template Your Node Application How to Install Node.js on Ubuntu (Step-by-Step Guide) MongoDB Indexes: Improve Query Performance with Node.js LLM Tool Calling with DigitalOcean AI Platform and Databases What are Text Diffusion Models? - An Overview Crafting a Game from Scratch with GPT-5.4 Building Long-Term Memory in AI Agents with LangGraph and Mem0 How To Install PHP 7.4 and Set Up a Local Development Environment on Ubuntu 20.04 Build a GraphQL API in Go to Upload Files to Spaces How To Lint and Format Code with ESLint in Visual Studio Code Train YOLO26 for Retail Object Detection on DigitalOcean GPUs How To Work with JSON in MySQL How to Use the JavaScript .map() Method Building a Scalable App with MongoDB Using DigitalOcean's MCP Server How to Create an SSH Key in Linux: Easy Step-by-Step Guide Measure MySQL Query Performance with mysqlslap How To Use *args and **kwargs in Python 3 Nemotron 3 helped me find the perfect dish rack? A2A vs MCP - How These AI Agent Protocols Actually Differ How To Install and Manage Supervisor Docker Container Images with Watchtower on Ubuntu Getting Started with Qwen3.5 Vision-Language Models How To Create a New Sudo-Enabled User on Ubuntu How to Use Ansible to Install and Set Up Docker on Ubuntu How To Enable Remote Desktop Protocol Using xrdp on Ubuntu 22.04 How To Convert a String to a List in Python How to Read a Properties File in Python Python Command Line Arguments: sys.argv, argparse, getopt Mastering Grep command in Linux/Unix: A Beginner's Tutorial Understanding Python Data Types How to Implement a Stack in C With Code Examples Python os.system() vs subprocess: Run System Commands How To Install and Use Docker Compose on Ubuntu How to Add and Delete Users on Ubuntu How To Order Query Results in Laravel Eloquent How To Define and Use Handlers in Ansible Playbooks How To Install and Use SQLite on Ubuntu How To Install and Use Homebrew on macOS How To Manage DateTime with Carbon in Laravel and PHP How To Install Git on Ubuntu How To Install and Secure Redis on Ubuntu How To Build and Install Go Programs on Linux Using ldflags to Set Version Information for Go Applications How To Build a Node.js Application with Docker How To Add JavaScript to HTML How To Reset Your MySQL or MariaDB Root Password How To Add Images in Markdown How To Set Up a Production Elasticsearch Cluster with Ansible How To Set Up a Firewall Using firewalld on CentOS Understanding Systemd Units and Unit Files How To Set Up Replication in MySQL How To Use the .htaccess File
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.