API数据字段仅支持ASCII编码,但我需要支持Unicode(表情符号、外文字符等)。
我想将用户输入的文本编码为转义的Unicode字符串:
let textContainingUnicode = """
Let's go in the .
And some new lines.
"""
let result = textContainingUnicode.unicodeScalars.map { $0.escaped(asASCII: true)}
.joined(separator: "")
.replacingOccurrences(
of: "\\\\u\\{(.+?(?=\\}))\\}", <- converting swift format \\u{****}
with: "\\\\U$1", <- into format python expects
options: .regularExpression)
result
这里是"让我们在\U0001F3CA中去\U0001F30A。\n还有一些新行。"
在服务器端使用Python进行解码:
codecs.decode("让我们在\\U0001F3CA中去\\U0001F30A。\\n还有一些新行。\n", 'unicode_escape')
但这听起来有些奇怪——我真的需要在Swift中进行如此多的字符串操作才能获得转义的Unicode吗?这些格式在不同的语言中是否都是标准化的。