def toXPathStringLiteral(s):
    if "'" not in s:
        return "'%s'" % s
if '"' not in s:
    return '"%s"' % s
return "concat('%s')" % s.replace("'", '\',"\'",\'')
"//span[@class='error'][contains(.,%s)]" % toXPathStringLiteral(message)
Escaping XPath literal with Python