字符串转义 / 反转义
对 JSON、JavaScript、HTML 字符串进行转义或反转义。
StringEscape.jsonDesc
StringEscape.cheatsheet
\→\\"→\"newline→\ntab→\tcarriage return→\rbackspace→\bform feed→\f常见问题
代码实现
import json
import html
import re
text = 'Hello "world"\nLine 2 & <tag>'
# JSON string escaping
json_escaped = json.dumps(text)
print(json_escaped)
# '"Hello \"world\"\nLine 2 & <tag>"'
# Python repr (Python string literal escaping)
py_escaped = repr(text)
print(py_escaped)
# '\'Hello "world"\nLine 2 & <tag>\''
# HTML escaping
html_escaped = html.escape(text)
print(html_escaped)
# 'Hello "world"\nLine 2 & <tag>'
# Regex escaping (escape metacharacters for use in pattern)
regex_escaped = re.escape("price: $4.99 (USD)")
print(regex_escaped)
# 'price:\ \$4\.99\ \(USD\)'Comments & Feedback
Comments are powered by Giscus. Sign in with GitHub to leave a comment.