我想搜索子字符串" can&#t; t"在Python中的字符串中。 这是代码:
astring = "I cant figure this out"
if "can\'t" in astring:
print "found it"
else:
print "did not find it"
上面应该打印"没有找到它"但是它打印"发现它"。如何正确转义单引号字符?
答案 0 :(得分:1)
astring = "I can't figure this out"
if 'can\'t' in astring:
print('yes')
答案 1 :(得分:0)
你必须在报价之前添加\。
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"
答案 2 :(得分:0)
一种方法是将字符串和正则表达式定义为原始字符串。然后,使用"' t"。
查找单词模式Sequence = Convert.ToInt32(fti.ItemName.Substring(fti.ItemName.LastIndexOf("_")+1))
输出
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")