如何在 Python 的字符串中搜索带引号的子字符串?

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

我想在 Python 中的字符串中搜索子字符串 "can't"。 这是代码:

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

上面应该打印 "did not find it",但是它打印 "found it"。如何正确转义单引号?

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

您必须在报价前添加\。

astring = "I cant figure this out"

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

或者你可以使用"find"方法,例如:

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

一种方法是将您的字符串和正则表达式定义为原始字符串。然后,寻找带有“'”的单词模式。

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")

输出

["can't"]