简体   繁体   English

将字符串转换为 unicode 转义序列

[英]Convert a string into a unicode escape sequence

I would like to convert a string to a unicode escape sequence, in python 3, that I can use later.我想将字符串转换为 unicode 转义序列,在 python 3 中,我可以稍后使用。 For example:例如:

string = "Hello, World!\n"
print(string.unicode_escape())
# shoud print \u0048\u0065\u006C\u006C\u006F\u002C\u0020...

Note the function should return a raw string or escape the backslashes (so I can actauly see the escape).请注意,该函数应返回一个原始字符串或转义反斜杠(因此我可以实际看到转义符)。 I have seen this post but it is not really related as it goes it over haskell.我看过这篇文章,但它并没有真正相关,因为它在 haskell 上进行了讨论。

The ord() function returns the Unicode code point of a character. ord()函数返回字符的 Unicode 代码点。 Just format this as \\u\u003c/code> followed by a 4-digit hex representation of that.只需将其格式化为\\u\u003c/code>后跟一个 4 位十六进制表示。

def unicode_escape(s):
    return "".join(map(lambda c: rf"\u{ord(c):04x}", s))
print(unicode_escape("Hello, World!\n"))
# prints \u0048\u0065\u006c\u006c\u006f\u002c\u0020\u0057\u006f\u0072\u006c\u0064\u0021\u000a
def encode(s): ret = [] for c in s: n = ord(c) ret.append("\\u{:04x}".format(n)) return "".join(ret) # print(encode("aeiouäöüßéá€æÆΑαΒβΓγ"))

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM