我尝试在Python中的字符串上替换用引号样式(“…”和“…”)标记的字符串。在
我已经写了一个正则表达式来代替标准引用
print re.sub(r'\"(.+?)\"', r'<em>"\1"</em>', self.title)
当我试图为文学作品做这件事时(?)它不能取代任何东西。在
^{pr2}$事实上,正如我现在所掌握的,我甚至不能进行条件查询:
quote_list = ['“', '”']
if all(character in self.title for character in quote_list):
print "It has literary quotes"
print re.sub(r'\“(.+?)\”', r'<em>“\1”</em>', self.title)
print re.sub(r'\"(.+?)\"', r'<em>"\1"</em>', self.title)
编辑:进一步的上下文:它是一个对象
class Entry(models.Model):
title = models.CharField(max_length=200)
def render_title(self):
"""
This function wraps italics around quotation marks
"""
quote_list = ['“', '”']
if all(character in self.title for character in quote_list):
print "It has literary quotes"
return re.sub(r'\“(.+?)\”', r'<em>“\1”</em>', self.title)
return re.sub(r'\"(.+?)\"', r'<em>"\1"</em>', self.title)
我不太精通regex命令。我做错什么了?在
离问题更近一步!这取决于我处理的是单子串。我还不知道该怎么解决这个问题。感谢任何帮助!在
>>> title = u"sdsfgsdfgsdgfsdgs “ asd” asd"
>>> print re.sub(r'\“(.+?)\”', r'<em>“\1”</em>', title)
sdsfgsdfgsdgfsdgs “ asd” asd
>>> title = "sdsfgsdfgsdgfsdgs “ asd” asd"
>>> print re.sub(r'\“(.+?)\”', r'<em>“\1”</em>', title)
sdsfgsdfgsdgfsdgs <em>“ asd”</em> asd
all
当每个元素为Truthy
时返回true在比较或使用regexpression时,请确保编码格式是相同的。支持对unicode字符串使用unicode regexp模式
^{pr2}$我终于找到了答案。在按@interjay的建议打印变量后,我发现字符串是unicoded。在
将它与一个简单的字符串进行比较不起作用,所以我删除了条件,并使用这个answer简单地生成一个unicode转义regex字符串来处理简单和“文学”引号。在
我在这里看到了一条评论(不幸的是现在被删除了)如何把上面的两个句子合并成一个句子,但是现在它起作用了。在
非常感谢你的帮助!在
相关问题 更多 >
编程相关推荐