didjek
didjek

Reputation: 451

How do I search for a substring with a quotation mark inside a string in Python?

I want to search for the substring "can't" inside a string in Python. Here is the code:

astring = "I cant figure this out"
if "can\'t" in astring:
    print "found it"
else:
    print "did not find it"

The above should print "did not find it", however it prints "found it". How do I escape the single quotation character correctly?

Upvotes: 3

Views: 3409

Answers (3)

Deepak Nagarajan
Deepak Nagarajan

Reputation: 131

One way is to define your string and regular expression as raw string. Then, look for a word pattern with "'t".

import re

string = r"can cant can't"
re_pattern = r"(\S+'t)"
re_obj = re.compile(re_pattern)
match = re_obj.findall(string)
if match:
    print(match)
else:
    print("no match found")

Output

["can't"]

Upvotes: 0

Roni
Roni

Reputation: 604

you have to add \ before quotation.

astring = "I cant figure this out"

if "can\'t" in astring:
    print "found it"
else:
    print "did not find it"

or you can use "find" method, for example :

if astring.find("can\'t")>-1:
    print "found it"
else:
    print "did not find it"

Upvotes: 3

noise
noise

Reputation: 127

astring = "I can't figure this out"    
if 'can\'t' in astring:
        print('yes')

Upvotes: 1

Related Questions