FaCoffee
FaCoffee

Reputation: 7929

Python: find exact phrase in string

I am not very familiar with string manipulation, and I am trying to find a way to determine if, given a text string and a phrase, that phrase appears in the string following the very same order it is given.

Example:
string='This question will probably be down voted because I am not able to post a minimal, complete, and verifiable example.'

phrase='I will not be down voted.'

Since the phrase does not appear in the same order in the string, this is not a match. I know it is possible to find if a word is part of a string, such as:

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

but how to check if an entire phrase is present in the string with in the original order?

Upvotes: 0

Views: 4018

Answers (3)

P.Panayotov
P.Panayotov

Reputation: 573

There are three ways that I can think of:

  1. With in opetor:

    phase in string

2.With string.find(substring) - will return None if the phase is not in the string.

  1. With re.search - re is package in python

re.search(pattern, string)

Upvotes: 1

If I am getting it right, you can do that as you did to find a word in a given string :

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

correct me if i'm wrong about what you're asking for.

Upvotes: 2

rosaqq
rosaqq

Reputation: 426

Not sure if I understand your question very well but as someone commented, you can use the keyword in to test for a specific phrase inside a string:

'my specific phrase' in 'my string with my specific phrase' will return True.

However 'my specific phrase' in 'my string specific phrase' will return False because even though the words are there, they are not in the same order.

Upvotes: 1

Related Questions