If word in string пример python

I’m working with Python, and I’m trying to find out if you can tell if a word is in a string.

I have found some information about identifying if the word is in the string — using .find, but is there a way to do an if statement. I would like to have something like the following:

if string.find(word):
    print("success")

mkrieger1's user avatar

mkrieger1

17.7k4 gold badges54 silver badges62 bronze badges

asked Mar 16, 2011 at 1:10

The Woo's user avatar

0

What is wrong with:

if word in mystring: 
   print('success')

Martin Thoma's user avatar

Martin Thoma

121k154 gold badges603 silver badges926 bronze badges

answered Mar 16, 2011 at 1:13

fabrizioM's user avatar

fabrizioMfabrizioM

46k15 gold badges100 silver badges118 bronze badges

13

if 'seek' in 'those who seek shall find':
    print('Success!')

but keep in mind that this matches a sequence of characters, not necessarily a whole word — for example, 'word' in 'swordsmith' is True. If you only want to match whole words, you ought to use regular expressions:

import re

def findWholeWord(w):
    return re.compile(r'b({0})b'.format(w), flags=re.IGNORECASE).search

findWholeWord('seek')('those who seek shall find')    # -> <match object>
findWholeWord('word')('swordsmith')                   # -> None

answered Mar 16, 2011 at 1:52

Hugh Bothwell's user avatar

Hugh BothwellHugh Bothwell

54.7k8 gold badges84 silver badges99 bronze badges

6

If you want to find out whether a whole word is in a space-separated list of words, simply use:

def contains_word(s, w):
    return (' ' + w + ' ') in (' ' + s + ' ')

contains_word('the quick brown fox', 'brown')  # True
contains_word('the quick brown fox', 'row')    # False

This elegant method is also the fastest. Compared to Hugh Bothwell’s and daSong’s approaches:

>python -m timeit -s "def contains_word(s, w): return (' ' + w + ' ') in (' ' + s + ' ')" "contains_word('the quick brown fox', 'brown')"
1000000 loops, best of 3: 0.351 usec per loop

>python -m timeit -s "import re" -s "def contains_word(s, w): return re.compile(r'b({0})b'.format(w), flags=re.IGNORECASE).search(s)" "contains_word('the quick brown fox', 'brown')"
100000 loops, best of 3: 2.38 usec per loop

>python -m timeit -s "def contains_word(s, w): return s.startswith(w + ' ') or s.endswith(' ' + w) or s.find(' ' + w + ' ') != -1" "contains_word('the quick brown fox', 'brown')"
1000000 loops, best of 3: 1.13 usec per loop

Edit: A slight variant on this idea for Python 3.6+, equally fast:

def contains_word(s, w):
    return f' {w} ' in f' {s} '

answered Apr 11, 2016 at 20:32

user200783's user avatar

user200783user200783

13.6k11 gold badges67 silver badges132 bronze badges

6

You can split string to the words and check the result list.

if word in string.split():
    print("success")

Martin Thoma's user avatar

Martin Thoma

121k154 gold badges603 silver badges926 bronze badges

answered Dec 1, 2016 at 18:26

Corvax's user avatar

CorvaxCorvax

7647 silver badges12 bronze badges

3

find returns an integer representing the index of where the search item was found. If it isn’t found, it returns -1.

haystack = 'asdf'

haystack.find('a') # result: 0
haystack.find('s') # result: 1
haystack.find('g') # result: -1

if haystack.find(needle) >= 0:
  print('Needle found.')
else:
  print('Needle not found.')

Martin Thoma's user avatar

Martin Thoma

121k154 gold badges603 silver badges926 bronze badges

answered Mar 16, 2011 at 1:13

Matt Howell's user avatar

Matt HowellMatt Howell

15.6k7 gold badges48 silver badges56 bronze badges

0

This small function compares all search words in given text. If all search words are found in text, returns length of search, or False otherwise.

Also supports unicode string search.

def find_words(text, search):
    """Find exact words"""
    dText   = text.split()
    dSearch = search.split()

    found_word = 0

    for text_word in dText:
        for search_word in dSearch:
            if search_word == text_word:
                found_word += 1

    if found_word == len(dSearch):
        return lenSearch
    else:
        return False

usage:

find_words('çelik güray ankara', 'güray ankara')

Trang Oul's user avatar

answered Jun 22, 2012 at 22:51

Guray Celik's user avatar

Guray CelikGuray Celik

1,2811 gold badge14 silver badges13 bronze badges

0

If matching a sequence of characters is not sufficient and you need to match whole words, here is a simple function that gets the job done. It basically appends spaces where necessary and searches for that in the string:

def smart_find(haystack, needle):
    if haystack.startswith(needle+" "):
        return True
    if haystack.endswith(" "+needle):
        return True
    if haystack.find(" "+needle+" ") != -1:
        return True
    return False

This assumes that commas and other punctuations have already been stripped out.

IanS's user avatar

IanS

15.6k9 gold badges59 silver badges84 bronze badges

answered Jun 15, 2012 at 7:23

daSong's user avatar

daSongdaSong

4071 gold badge5 silver badges9 bronze badges

1

Using regex is a solution, but it is too complicated for that case.

You can simply split text into list of words. Use split(separator, num) method for that. It returns a list of all the words in the string, using separator as the separator. If separator is unspecified it splits on all whitespace (optionally you can limit the number of splits to num).

list_of_words = mystring.split()
if word in list_of_words:
    print('success')

This will not work for string with commas etc. For example:

mystring = "One,two and three"
# will split into ["One,two", "and", "three"]

If you also want to split on all commas etc. use separator argument like this:

# whitespace_chars = " tnrf" - space, tab, newline, return, formfeed
list_of_words = mystring.split( tnrf,.;!?'"()")
if word in list_of_words:
    print('success')

Martin Thoma's user avatar

Martin Thoma

121k154 gold badges603 silver badges926 bronze badges

answered Dec 18, 2017 at 11:44

tstempko's user avatar

tstempkotstempko

1,1761 gold badge15 silver badges17 bronze badges

2

As you are asking for a word and not for a string, I would like to present a solution which is not sensitive to prefixes / suffixes and ignores case:

#!/usr/bin/env python

import re


def is_word_in_text(word, text):
    """
    Check if a word is in a text.

    Parameters
    ----------
    word : str
    text : str

    Returns
    -------
    bool : True if word is in text, otherwise False.

    Examples
    --------
    >>> is_word_in_text("Python", "python is awesome.")
    True

    >>> is_word_in_text("Python", "camelCase is pythonic.")
    False

    >>> is_word_in_text("Python", "At the end is Python")
    True
    """
    pattern = r'(^|[^w]){}([^w]|$)'.format(word)
    pattern = re.compile(pattern, re.IGNORECASE)
    matches = re.search(pattern, text)
    return bool(matches)


if __name__ == '__main__':
    import doctest
    doctest.testmod()

If your words might contain regex special chars (such as +), then you need re.escape(word)

answered Aug 9, 2017 at 10:11

Martin Thoma's user avatar

Martin ThomaMartin Thoma

121k154 gold badges603 silver badges926 bronze badges

Advanced way to check the exact word, that we need to find in a long string:

import re
text = "This text was of edited by Rock"
#try this string also
#text = "This text was officially edited by Rock" 
for m in re.finditer(r"bofb", text):
    if m.group(0):
        print("Present")
    else:
        print("Absent")

Martin Thoma's user avatar

Martin Thoma

121k154 gold badges603 silver badges926 bronze badges

answered Nov 2, 2016 at 8:39

Rameez's user avatar

RameezRameez

5545 silver badges11 bronze badges

What about to split the string and strip words punctuation?

w in [ws.strip(',.?!') for ws in p.split()]

If need, do attention to lower/upper case:

w.lower() in [ws.strip(',.?!') for ws in p.lower().split()]

Maybe that way:

def wcheck(word, phrase):
    # Attention about punctuation and about split characters
    punctuation = ',.?!'
    return word.lower() in [words.strip(punctuation) for words in phrase.lower().split()]

Sample:

print(wcheck('CAr', 'I own a caR.'))

I didn’t check performance…

answered Dec 26, 2020 at 5:18

marcio's user avatar

marciomarcio

5067 silver badges19 bronze badges

You could just add a space before and after «word».

x = raw_input("Type your word: ")
if " word " in x:
    print("Yes")
elif " word " not in x:
    print("Nope")

This way it looks for the space before and after «word».

>>> Type your word: Swordsmith
>>> Nope
>>> Type your word:  word 
>>> Yes

Martin Thoma's user avatar

Martin Thoma

121k154 gold badges603 silver badges926 bronze badges

answered Feb 26, 2015 at 14:23

PyGuy's user avatar

PyGuyPyGuy

433 bronze badges

1

I believe this answer is closer to what was initially asked: Find substring in string but only if whole words?

It is using a simple regex:

import re

if re.search(r"b" + re.escape(word) + r"b", string):
  print('success')

Martin Thoma's user avatar

Martin Thoma

121k154 gold badges603 silver badges926 bronze badges

answered Aug 25, 2021 at 13:25

Milos Cuculovic's user avatar

Milos CuculovicMilos Cuculovic

19.4k50 gold badges159 silver badges264 bronze badges

One of the solutions is to put a space at the beginning and end of the test word. This fails if the word is at the beginning or end of a sentence or is next to any punctuation. My solution is to write a function that replaces any punctuation in the test string with spaces, and add a space to the beginning and end or the test string and test word, then return the number of occurrences. This is a simple solution that removes the need for any complex regex expression.

def countWords(word, sentence):
    testWord = ' ' + word.lower() + ' '
    testSentence = ' '

    for char in sentence:
        if char.isalpha():
            testSentence = testSentence + char.lower()
        else:
            testSentence = testSentence + ' '

    testSentence = testSentence + ' '

    return testSentence.count(testWord)

To count the number of occurrences of a word in a string:

sentence = "A Frenchman ate an apple"
print(countWords('a', sentence))

returns 1

sentence = "Is Oporto a 'port' in Portugal?"
print(countWords('port', sentence))

returns 1

Use the function in an ‘if’ to test if the word exists in a string

answered Mar 18, 2022 at 9:37

iStuart's user avatar

iStuartiStuart

3953 silver badges6 bronze badges

  1. HowTo
  2. Python How-To’s
  3. Check if a String Contains Word in …

Muhammad Maisam Abbas
Dec 21, 2022
Jun 07, 2021

Check if a String Contains Word in Python

This tutorial will introduce the method to find whether a specified word is inside a string variable or not in Python.

Check the String if It Contains a Word Through an if/in Statement in Python

If we want to check whether a given string contains a specified word in it or not, we can use the if/in statement in Python. The if/in statement returns True if the word is present in the string and False if the word is not in the string.

The following program snippet shows us how to use the if/in statement to determine whether a string contains a word or not:

string = "This contains a word"
if "word" in string:
    print("Found")
else:
    print("Not Found")

Output:

We checked whether the string variable string contains the word word inside it or not with the if/in statement in the program above. This approach compares both strings character-wise; this means that it doesn’t compare whole words and can give us wrong answers, as demonstrated in the following example:

string = "This contains a word"
if "is" in string:
    print("Found")
else:
    print("Not Found")

Output:

The output shows that the word is is present inside the string variable string. But, in reality, this is is just a part of the first word This in the string variable.

This problem has a simple solution. We can surround the word and the string variable with white spaces to just compare the whole word. The program below shows us how we can do that:

string = "This contains a word"
if " is " in (" " + string + " "):
    print("Found")
else:
    print("Not Found")

Output:

In the code above, we used the same if/in statement, but we slightly altered it to compare only individual words. This time, the output shows no such word as is present inside the string variable.

Muhammad Maisam Abbas avatar
Muhammad Maisam Abbas avatar

Maisam is a highly skilled and motivated Data Scientist. He has over 4 years of experience with Python programming language. He loves solving complex problems and sharing his results on the internet.

LinkedIn

Related Article — Python String

  • Remove Commas From String in Python
  • Check a String Is Empty in a Pythonic Way
  • Convert a String to Variable Name in Python
  • Remove Whitespace From a String in Python
  • Extract Numbers From a String in Python
  • Convert String to Datetime in Python

Ezoic

Watch Now This tutorial has a related video course created by the Real Python team. Watch it together with the written tutorial to deepen your understanding: Check if a Python String Contains a Substring

If you’re new to programming or come from a programming language other than Python, you may be looking for the best way to check whether a string contains another string in Python.

Identifying such substrings comes in handy when you’re working with text content from a file or after you’ve received user input. You may want to perform different actions in your program depending on whether a substring is present or not.

In this tutorial, you’ll focus on the most Pythonic way to tackle this task, using the membership operator in. Additionally, you’ll learn how to identify the right string methods for related, but different, use cases.

Finally, you’ll also learn how to find substrings in pandas columns. This is helpful if you need to search through data from a CSV file. You could use the approach that you’ll learn in the next section, but if you’re working with tabular data, it’s best to load the data into a pandas DataFrame and search for substrings in pandas.

How to Confirm That a Python String Contains Another String

If you need to check whether a string contains a substring, use Python’s membership operator in. In Python, this is the recommended way to confirm the existence of a substring in a string:

>>>

>>> raw_file_content = """Hi there and welcome.
... This is a special hidden file with a SECRET secret.
... I don't want to tell you The Secret,
... but I do want to secretly tell you that I have one."""

>>> "secret" in raw_file_content
True

The in membership operator gives you a quick and readable way to check whether a substring is present in a string. You may notice that the line of code almost reads like English.

When you use in, the expression returns a Boolean value:

  • True if Python found the substring
  • False if Python didn’t find the substring

You can use this intuitive syntax in conditional statements to make decisions in your code:

>>>

>>> if "secret" in raw_file_content:
...    print("Found!")
...
Found!

In this code snippet, you use the membership operator to check whether "secret" is a substring of raw_file_content. If it is, then you’ll print a message to the terminal. Any indented code will only execute if the Python string that you’re checking contains the substring that you provide.

The membership operator in is your best friend if you just need to check whether a Python string contains a substring.

However, what if you want to know more about the substring? If you read through the text stored in raw_file_content, then you’ll notice that the substring occurs more than once, and even in different variations!

Which of these occurrences did Python find? Does capitalization make a difference? How often does the substring show up in the text? And what’s the location of these substrings? If you need the answer to any of these questions, then keep on reading.

Generalize Your Check by Removing Case Sensitivity

Python strings are case sensitive. If the substring that you provide uses different capitalization than the same word in your text, then Python won’t find it. For example, if you check for the lowercase word "secret" on a title-case version of the original text, the membership operator check returns False:

>>>

>>> title_cased_file_content = """Hi There And Welcome.
... This Is A Special Hidden File With A Secret Secret.
... I Don't Want To Tell You The Secret,
... But I Do Want To Secretly Tell You That I Have One."""

>>> "secret" in title_cased_file_content
False

Despite the fact that the word secret appears multiple times in the title-case text title_cased_file_content, it never shows up in all lowercase. That’s why the check that you perform with the membership operator returns False. Python can’t find the all-lowercase string "secret" in the provided text.

Humans have a different approach to language than computers do. This is why you’ll often want to disregard capitalization when you check whether a string contains a substring in Python.

You can generalize your substring check by converting the whole input text to lowercase:

>>>

>>> file_content = title_cased_file_content.lower()

>>> print(file_content)
hi there and welcome.
this is a special hidden file with a secret secret.
i don't want to tell you the secret,
but i do want to secretly tell you that i have one.

>>> "secret" in file_content
True

Converting your input text to lowercase is a common way to account for the fact that humans think of words that only differ in capitalization as the same word, while computers don’t.

Now that you’ve converted the string to lowercase to avoid unintended issues stemming from case sensitivity, it’s time to dig further and learn more about the substring.

Learn More About the Substring

The membership operator in is a great way to descriptively check whether there’s a substring in a string, but it doesn’t give you any more information than that. It’s perfect for conditional checks—but what if you need to know more about the substrings?

Python provides many additonal string methods that allow you to check how many target substrings the string contains, to search for substrings according to elaborate conditions, or to locate the index of the substring in your text.

In this section, you’ll cover some additional string methods that can help you learn more about the substring.

By using in, you confirmed that the string contains the substring. But you didn’t get any information on where the substring is located.

If you need to know where in your string the substring occurs, then you can use .index() on the string object:

>>>

>>> file_content = """hi there and welcome.
... this is a special hidden file with a secret secret.
... i don't want to tell you the secret,
... but i do want to secretly tell you that i have one."""

>>> file_content.index("secret")
59

When you call .index() on the string and pass it the substring as an argument, you get the index position of the first character of the first occurrence of the substring.

But what if you want to find other occurrences of the substring? The .index() method also takes a second argument that can define at which index position to start looking. By passing specific index positions, you can therefore skip over occurrences of the substring that you’ve already identified:

>>>

>>> file_content.index("secret", 60)
66

When you pass a starting index that’s past the first occurrence of the substring, then Python searches starting from there. In this case, you get another match and not a ValueError.

That means that the text contains the substring more than once. But how often is it in there?

You can use .count() to get your answer quickly using descriptive and idiomatic Python code:

>>>

>>> file_content.count("secret")
4

You used .count() on the lowercase string and passed the substring "secret" as an argument. Python counted how often the substring appears in the string and returned the answer. The text contains the substring four times. But what do these substrings look like?

You can inspect all the substrings by splitting your text at default word borders and printing the words to your terminal using a for loop:

>>>

>>> for word in file_content.split():
...    if "secret" in word:
...        print(word)
...
secret
secret.
secret,
secretly

In this example, you use .split() to separate the text at whitespaces into strings, which Python packs into a list. Then you iterate over this list and use in on each of these strings to see whether it contains the substring "secret".

Now that you can inspect all the substrings that Python identifies, you may notice that Python doesn’t care whether there are any characters after the substring "secret" or not. It finds the word whether it’s followed by whitespace or punctuation. It even finds words such as "secretly".

That’s good to know, but what can you do if you want to place stricter conditions on your substring check?

Find a Substring With Conditions Using Regex

You may only want to match occurrences of your substring followed by punctuation, or identify words that contain the substring plus other letters, such as "secretly".

For such cases that require more involved string matching, you can use regular expressions, or regex, with Python’s re module.

For example, if you want to find all the words that start with "secret" but are then followed by at least one additional letter, then you can use the regex word character (w) followed by the plus quantifier (+):

>>>

>>> import re

>>> file_content = """hi there and welcome.
... this is a special hidden file with a secret secret.
... i don't want to tell you the secret,
... but i do want to secretly tell you that i have one."""

>>> re.search(r"secretw+", file_content)
<re.Match object; span=(128, 136), match='secretly'>

The re.search() function returns both the substring that matched the condition as well as its start and end index positions—rather than just True!

You can then access these attributes through methods on the Match object, which is denoted by m:

>>>

>>> m = re.search(r"secretw+", file_content)

>>> m.group()
'secretly'

>>> m.span()
(128, 136)

These results give you a lot of flexibility to continue working with the matched substring.

For example, you could search for only the substrings that are followed by a comma (,) or a period (.):

>>>

>>> re.search(r"secret[.,]", file_content)
<re.Match object; span=(66, 73), match='secret.'>

There are two potential matches in your text, but you only matched the first result fitting your query. When you use re.search(), Python again finds only the first match. What if you wanted all the mentions of "secret" that fit a certain condition?

To find all the matches using re, you can work with re.findall():

>>>

>>> re.findall(r"secret[.,]", file_content)
['secret.', 'secret,']

By using re.findall(), you can find all the matches of the pattern in your text. Python saves all the matches as strings in a list for you.

When you use a capturing group, you can specify which part of the match you want to keep in your list by wrapping that part in parentheses:

>>>

>>> re.findall(r"(secret)[.,]", file_content)
['secret', 'secret']

By wrapping secret in parentheses, you defined a single capturing group. The findall() function returns a list of strings matching that capturing group, as long as there’s exactly one capturing group in the pattern. By adding the parentheses around secret, you managed to get rid of the punctuation!

Using re.findall() with match groups is a powerful way to extract substrings from your text. But you only get a list of strings, which means that you’ve lost the index positions that you had access to when you were using re.search().

If you want to keep that information around, then re can give you all the matches in an iterator:

>>>

>>> for match in re.finditer(r"(secret)[.,]", file_content):
...    print(match)
...
<re.Match object; span=(66, 73), match='secret.'>
<re.Match object; span=(103, 110), match='secret,'>

When you use re.finditer() and pass it a search pattern and your text content as arguments, you can access each Match object that contains the substring, as well as its start and end index positions.

You may notice that the punctuation shows up in these results even though you’re still using the capturing group. That’s because the string representation of a Match object displays the whole match rather than just the first capturing group.

But the Match object is a powerful container of information and, like you’ve seen earlier, you can pick out just the information that you need:

>>>

>>> for match in re.finditer(r"(secret)[.,]", file_content):
...    print(match.group(1))
...
secret
secret

By calling .group() and specifying that you want the first capturing group, you picked the word secret without the punctuation from each matched substring.

You can go into much more detail with your substring matching when you use regular expressions. Instead of just checking whether a string contains another string, you can search for substrings according to elaborate conditions.

Using regular expressions with re is a good approach if you need information about the substrings, or if you need to continue working with them after you’ve found them in the text. But what if you’re working with tabular data? For that, you’ll turn to pandas.

Find a Substring in a pandas DataFrame Column

If you work with data that doesn’t come from a plain text file or from user input, but from a CSV file or an Excel sheet, then you could use the same approach as discussed above.

However, there’s a better way to identify which cells in a column contain a substring: you’ll use pandas! In this example, you’ll work with a CSV file that contains fake company names and slogans. You can download the file below if you want to work along:

When you’re working with tabular data in Python, it’s usually best to load it into a pandas DataFrame first:

>>>

>>> import pandas as pd

>>> companies = pd.read_csv("companies.csv")

>>> companies.shape
(1000, 2)

>>> companies.head()
             company                                     slogan
0      Kuvalis-Nolan      revolutionize next-generation metrics
1  Dietrich-Champlin  envisioneer bleeding-edge functionalities
2           West Inc            mesh user-centric infomediaries
3         Wehner LLC               utilize sticky infomediaries
4      Langworth Inc                 reinvent magnetic networks

In this code block, you loaded a CSV file that contains one thousand rows of fake company data into a pandas DataFrame and inspected the first five rows using .head().

After you’ve loaded the data into the DataFrame, you can quickly query the whole pandas column to filter for entries that contain a substring:

>>>

>>> companies[companies.slogan.str.contains("secret")]
              company                                  slogan
7          Maggio LLC                    target secret niches
117      Kub and Sons              brand secret methodologies
654       Koss-Zulauf              syndicate secret paradigms
656      Bernier-Kihn  secretly synthesize back-end bandwidth
921      Ward-Shields               embrace secret e-commerce
945  Williamson Group             unleash secret action-items

You can use .str.contains() on a pandas column and pass it the substring as an argument to filter for rows that contain the substring.

When you’re working with .str.contains() and you need more complex match scenarios, you can also use regular expressions! You just need to pass a regex-compliant search pattern as the substring argument:

>>>

>>> companies[companies.slogan.str.contains(r"secretw+")]
          company                                  slogan
656  Bernier-Kihn  secretly synthesize back-end bandwidth

In this code snippet, you’ve used the same pattern that you used earlier to match only words that contain secret but then continue with one or more word character (w+). Only one of the companies in this fake dataset seems to operate secretly!

You can write any complex regex pattern and pass it to .str.contains() to carve from your pandas column just the rows that you need for your analysis.

Conclusion

Like a persistent treasure hunter, you found each "secret", no matter how well it was hidden! In the process, you learned that the best way to check whether a string contains a substring in Python is to use the in membership operator.

You also learned how to descriptively use two other string methods, which are often misused to check for substrings:

  • .count() to count the occurrences of a substring in a string
  • .index() to get the index position of the beginning of the substring

After that, you explored how to find substrings according to more advanced conditions with regular expressions and a few functions in Python’s re module.

Finally, you also learned how you can use the DataFrame method .str.contains() to check which entries in a pandas DataFrame contain a substring .

You now know how to pick the most idiomatic approach when you’re working with substrings in Python. Keep using the most descriptive method for the job, and you’ll write code that’s delightful to read and quick for others to understand.

Watch Now This tutorial has a related video course created by the Real Python team. Watch it together with the written tutorial to deepen your understanding: Check if a Python String Contains a Substring

In this Python tutorial, we will discuss everything on Python find substring in string with a few more examples.

Python provides several methods to find substrings in a string. Here we will discuss 12 different methods to check if Python String contains a substring.

  • Using the in operator
  • Using The find() method
  • Using the index() method
  • Using the re module
  • Using the startswith() method
  • Using the endswith() method
  • Using the split() method
  • Using the partition() method
  • Using the count() method
  • Using the rfind() method
  • Using the list comprehension
  • Using the re.findall()

Method-1: Using the in operator

The in operator is one of the simplest and quickest ways to check if a substring is present in a string. It returns True if the substring is found and False otherwise.

# Define the main string
string = "I live in USA"

# Define the substring to be searched
substring = "USA"

# Use 'in' operator to check if substring is present in string
if substring in string:
    print("Substring found")
else:
    print("Substring not found")

The above code checks if a given substring is present in a given string.

  • The main string is stored in the variable string and the substring to be searched is stored in the variable substring.
  • The code uses the in operator to check if the substring is present in the string. If it is, the code outputs “Substring found” to the console. If not, the code outputs “Substring not found”.
Python find substring in string using the in operator
Python find substring in string using the in operator

Read: Slicing string in Python + Examples

Method-2: Using The find() method

The find() method is another simple way to find substrings in a string. It returns the index of the first occurrence of the substring in the string. If the substring is not found, it returns -1.

# Define the main string
string = "I live in USA"

# Define the substring to be searched
substring = "USA"

# Use the find() method to get the index of the substring
index = string.find(substring)

# Check if the substring is found
if index != -1:
    print("Substring found at index", index)
else:
    print("Substring not found")

The above code uses the find() method to search for the index of a given substring in a given string.

  • The find() method is used to search for the index of the substring in the string, and the result is stored in the variable index.
  • If the substring is found, the index will be set to the index of the first character of the substring in the string. If the substring is not found, index will be set to -1.
  • The code then checks if index is not equal to -1. If it is not, the substring was found and the code outputs “Substring found at index” followed by the value of the index.
  • If the index is equal to -1, the substring was not found and the code outputs “Substring not found”.
Python find substring in string using the find method
Python find substring in string using the find method

Read: Convert string to float in Python

Method-3: Using the index() method

The index() method is similar to the find() method, but it raises a ValueError exception if the substring is not found in the string.

# Search for substring in a given string
string = "I live in USA"

# The substring we want to search for
substring = "live"

# Use try-except block to handle potential ValueError if substring is not found
try:
    # Find the index of the substring in the string using the index() method
    index = string.index(substring)
    # Print a success message with the index of the substring
    print("Substring found at index", index)
except ValueError:
    # If the substring is not found, print a message indicating that it was not found
    print("Substring not found")

The code above is checking if a given substring is present in a string.

  • The input string is “I live in USA” and the substring we want to search for is “live”.
  • The code uses a try-except block to handle the potential error of not finding the substring in the string.
  • The index() method is used to find the index of the substring in the string. If the substring is found, the code prints a message indicating the index of the substring in the string.
  • If the substring is not found, a ValueError is raised, which is caught by the except block, and a message indicating that the substring was not found is printed.
Python find substring in string using the index method
Python find substring in string using the index method

Read: Append to a string Python + Examples

Method-4: Using the re module

The re (regular expression) module provides powerful methods for matching and searching for substrings in a string.

# Use the re module for pattern matching
import re

# The string we want to search in
string = "I live in USA"

# The substring we want to search for
substring = "in"

# Use the search() method from the re module to find a match
match = re.search(substring, string)

# Check if a match was found
if match:
    # If a match was found, print a success message
    print("Substring found")
else:
    # If no match was found, print a failure message
    print("Substring not found")

The code above is checking if a given substring is present in a string using regular expressions (regex).

  • The first line import re imports the re module which provides functions for pattern matching in strings.
  • The input string is “I live in USA” and the substring we want to search for is “in”. The code then uses the re.search() method to find a match between the substring and the input string.
  • The re.search() method returns a match object if there is a match between the substring and the input string, otherwise it returns None.
  • The code then uses an if statement to check if a match was found. If a match was found, the code prints a message indicating that the substring was found.
  • If no match was found, the code prints a message indicating that the substring was not found.
Python find substring in string using the re module
Python find substring in string using the re module

Read: Python compare strings

Method-5: Using the startswith() method

The startswith() method returns True if the string starts with the specified substring and False otherwise.

# The string we want to search in
string = "I live in USA"

# The substring we want to search for
substring = "I"

# Use the startswith() method to check if the string starts with the substring
if string.startswith(substring):
    # If the string starts with the substring, print a success message
    print("Substring found")
else:
    # If the string does not start with the substring, print a failure message
    print("Substring not found")

The code above checks if a given substring is at the beginning of a string.

  • The input string is “I live in USA” and the substring we want to search for is “I”. The code uses the startswith() method to check if the input string starts with the substring.
  • The startswith() method returns True if the input string starts with the substring and False otherwise. The code then uses an if statement to check the result of the startswith() method.
  • If the input string starts with the substring, the code prints a message indicating that the substring was found. If the input string does not start with the substring, the code prints a message indicating that the substring was not found.
Python find substring in string using the startswith method
Python find substring in string using the startswith method

Read: Python program to reverse a string with examples

Method-6: Using the endswith() method

The endswith() method is similar to the startswith() method, but it returns True if the string ends with the specified substring and False otherwise.

# The string we want to search in
string = "I live in USA"

# The substring we want to search for
substring = "USA"

# Use the endswith() method to check if the string ends with the substring
if string.endswith(substring):
    # If the string ends with the substring, print a success message
    print("Substring found")
else:
    # If the string does not end with the substring, print a failure message
    print("Substring not found")

The code above checks if a given substring is at the end of a string.

  • The input string is “I live in USA” and the substring we want to search for is “USA”. The code uses the endswith() method to check if the input string ends with the substring.
  • The endswith() method returns True if the input string ends with the substring and False otherwise. The code then uses an if statement to check the result of the endswith() method.
  • If the input string ends with the substring, the code prints a message indicating that the substring was found. If the input string does not end with the substring, the code prints a message indicating that the substring was not found.
Python find substring in string using the endswith method
Python find substring in string using the endswith method

Read: Python string formatting with examples.

Method-7: Using the split() method

The split() method splits a string into a list of substrings based on a specified delimiter. The resulting substrings can then be searched for the desired substring.

# The string we want to search in
string = "I live in USA"

# The substring we want to search for
substring = "USA"

# Split the string into substrings using the split() method and store the result in a list
substrings = string.split(" ")

# Check if the substring is in the list of substrings
if substring in substrings:
    # If the substring is in the list, print a success message
    print("Substring found")
else:
    # If the substring is not in the list, print a failure message
    print("Substring not found")

The code above checks if a given substring is contained within a string.

  • The input string is “I live in USA” and the substring we want to search for is “USA”. The code splits the input string into substrings using the split() method and stores the result in a list substrings.
  • The split() method splits a string into substrings using a specified delimiter (in this case, a space character).
  • Next, the code uses the in operator to check if the substring is in the list of substrings. If the substring is in the list, the code prints a message indicating that the substring was found.
  • If the substring is not in the list, the code prints a message indicating that the substring was not found.
Python find substring in string using the split method
Python find substring in string using the split method

Method-8: Using the partition() method

The partition() method splits a string into a tuple of three substrings: the substring before the specified delimiter, the specified delimiter, and the substring after the specified delimiter.

# The string we want to search in
string = "I live in USA"

# The substring we want to search for
substring = "I"

# Use the partition() method to split the string into three parts
before, delimiter, after = string.partition(" ")

# Check if the first part of the split string is equal to the substring
if before == substring:
    # If the first part is equal to the substring, print a success message
    print("Substring found")
else:
    # If the first part is not equal to the substring, print a failure message
    print("Substring not found")

The code above checks if a given substring is at the beginning of a string.

The input string is “I live in USA” and the substring we want to search for is “I”. The code uses the partition() method to split the input string into three parts:

  • The part before the specified delimiter, the delimiter itself, and the part after the delimiter. In this case, the delimiter is a space character.
  • The partition() method returns a tuple with three elements: the part before the delimiter, the delimiter itself, and the part after the delimiter.
  • The code uses tuple unpacking to assign the three parts to the variables before, delimiter, and after.
  • Next, the code uses an if statement to check if the first part of the split string (i.e., before) is equal to the substring.
  • If the first part is equal to the substring, the code prints a message indicating that the substring was found. If the first part is not equal to the substring, the code prints a message indicating that the substring was not found.
Python find substring in string using the partition method
Python find substring in string using the partition method

Method-9: Using the count() method

The count() method returns the number of times a substring appears in a string.

# The string we want to search in
string = "I live in USA"

# The substring we want to search for
substring = "live"

# Use the count() method to count the number of times the substring appears in the string
count = string.count(substring)

# Print the result
print("Substring found", count, "times")

The code above counts the number of times a given substring appears in a string.

  • The input string is “I live in USA” and the substring we want to search for is “live”. The code uses the count() method to count the number of times the substring appears in the string.
  • Finally, the code uses the print() function to print the result, indicating how many times the substring was found in the string.
Python find substring in string using the count method
Python find substring in string using the count method

Method-10: Using the rfind() method

The rfind() method is similar to the find() method, but it returns the index of the last occurrence of the substring in the string. If the substring is not found, it returns -1.

# The string we want to search in
string = "I live in USA"

# The substring we want to search for
substring = "USA"

# Use the rfind() method to find the last index of the substring in the string
index = string.rfind(substring)

# Check if the substring was found
if index != -1:
    # If the substring was found, print the index
    print("Substring found at index", index)
else:
    # If the substring was not found, print a message
    print("Substring not found")

The code above searches for the last occurrence of a given substring in a string.

  • The input string is “I live in USA” and the substring we want to search for is “USA”. The code uses the rfind() method to find the last index of the substring in the string.
  • The rfind() method returns the index of the last occurrence of the substring in the string, or -1 if the substring is not found. So the code checks if the returned value is not equal to -1, indicating that the substring was found in the string.
  • Finally, the code uses the print() function to print the result, indicating the index of the last occurrence of the substring in the string.
Python find substring in string using the rfind method
Python find substring in string using the rfind method

Method-11: Using the list comprehension

# The string we want to search in
string = "I live in USA"

# The substring we want to search for
substring = "USA"

# Use a list comprehension to find if the substring exists in the string split into words
result = [word for word in string.split() if word == substring]

# Check if the result list is not empty
if result:
    # If the result list is not empty, the substring was found
    print("Substring found")
else:
    # If the result list is empty, the substring was not found
    print("Substring not found")

The code above checks if a given substring exists in a string.

  • The input string is “I live in USA” and the substring we want to search for is “USA”. The code uses a list comprehension to create a list of words from the input string, where each word is checked if it is equal to the given substring.
  • The list comprehension iterates over the words in the input string, which is split using the split() method, and adds the word to the result list if it is equal to the given substring.
  • Finally, the code uses an if statement to check if the result list is not empty. If the result list is not empty, it means that the substring was found in the input string, so the code prints “Substring found”.
  • If the result list is empty, the substring was not found in the input string, so the code prints “Substring not found”.
Python find substring in string using the list comprehension
Python find substring in string using the list comprehension

Method-12: Using the re.findall()

The re.findall() function returns a list of all non-overlapping matches of the specified pattern within the string. We can use this function to find all occurrences of a substring within a string by specifying the substring as the pattern.

# Import the regular expression library 're'
import re

# The input text to search for the substring
text = "I live in USA"

# The substring to search for in the text
substring = "USA"

# Find all occurrences of the substring in the text using the 'findall' method from the 're' library
result = re.findall(substring, text)

# Print the result
print(result)

In the above code, the regular expression library re is imported and used to find all occurrences of the given substring “USA” in the input text “I live in USA”.

  • The re.findall method is used to search for all occurrences of the substring in the text and return them as a list.
  • Finally, the result is printed on the console.

You may like the following Python examples:

  • How to concatenate strings in python
  • Find Last Number in String in Python
  • Find first number in string in Python

In this Python tutorial, we learned, Python find substring in string using the below methods:

  • Python find substring in string using the in operator
  • Python find substring in string using The find() method
  • Python find substring in string using the index() method
  • Python find substring in string using the re module
  • Python find substring in string using the startswith() method
  • Python find substring in string using the endswith() method
  • Python find substring in string using the split() method
  • Python find substring in string using the partition() method
  • Python find substring in string using the count() method
  • Python find substring in string using the rfind() method
  • Python find substring in string using the list comprehension
  • Python find substring in string using the re.findall()

Bijay Kumar MVP

Python is one of the most popular languages in the United States of America. I have been working with Python for a long time and I have expertise in working with various libraries on Tkinter, Pandas, NumPy, Turtle, Django, Matplotlib, Tensorflow, Scipy, Scikit-Learn, etc… I have experience in working with various clients in countries like United States, Canada, United Kingdom, Australia, New Zealand, etc. Check out my profile.

Приветствую!
Произвожу поиск подстроки следующим образом:

if  'слово1' in string or 'слово2' in string  or 'слово3' in string:
    return True

Есть ли здесь возможность узнать какое именно условие сработало (какое слово было найдено)?
Или может есть другой способ при котором это было бы возможно?


  • Вопрос задан

    более трёх лет назад

  • 251 просмотр

words = ['слово1','слово2','слово3']
string = 'слово123'
{i:True for i in words if i in string}

==>
{'слово1':True}

if 'слово1' in string:
    # сработало первое
    return True
if 'слово2' in string:
    # сработало второе
    return True
if 'слово3' in string:
    # сработало третье
    return True

Еще можно в цикле:

words = ['слово1', 'слово2', 'слово3']
for word in words:
    if word in string:
        # найдено word
        return True

Пригласить эксперта

пошаговая отладка в помощь
думаю сразу поймешь что к чему

>>> def f(s):
...     words = ('слово1', 'слово2', 'слово3')
...     for w in words:
...         if w in s:
...             return w
... 
>>> f('abc слово2 def слово1 ghi')
'слово1'
>>> f('abc def ghi')
>>>


  • Показать ещё
    Загружается…

14 апр. 2023, в 09:27

500 руб./за проект

14 апр. 2023, в 09:25

100000 руб./за проект

14 апр. 2023, в 08:46

30000 руб./за проект

Минуточку внимания

Like this post? Please share to your friends:
  • If word in dict python
  • If with vlookup excel на русском
  • If with range of values in excel
  • If with nested and in excel
  • If with and in excel 2013