Convert a string into unicode escape sequences
Question:
How can I convert a string so that each character is replaced with the corresponding Unicode escape sequence?
Something like:
def unicode_escape(s):
"""How do I write this?"""
print(unicode_escape("Hello, World!n"))
# should print u0048u0065u006Cu006Cu006Fu002Cu0020...
Answers:
The ord()
function returns the Unicode code point of a character. Just format this as u
followed by a 4-digit hex representation of that.
def unicode_escape(s):
return "".join(map(lambda c: rf"u{ord(c):04x}", s))
print(unicode_escape("Hello, World!n"))
# prints u0048u0065u006cu006cu006fu002cu0020u0057u006fu0072u006cu0064u0021u000a
def encode(s):
ret = []
for c in s:
n = ord(c)
ret.append("\u{:04x}".format(n))
return "".join(ret)
#
print(encode("aeiouäöüßéá€æÆΑαΒβΓγ"))
How can I convert a string so that each character is replaced with the corresponding Unicode escape sequence?
Something like:
def unicode_escape(s):
"""How do I write this?"""
print(unicode_escape("Hello, World!n"))
# should print u0048u0065u006Cu006Cu006Fu002Cu0020...
The ord()
function returns the Unicode code point of a character. Just format this as u
followed by a 4-digit hex representation of that.
def unicode_escape(s):
return "".join(map(lambda c: rf"u{ord(c):04x}", s))
print(unicode_escape("Hello, World!n"))
# prints u0048u0065u006cu006cu006fu002cu0020u0057u006fu0072u006cu0064u0021u000a
def encode(s):
ret = []
for c in s:
n = ord(c)
ret.append("\u{:04x}".format(n))
return "".join(ret)
#
print(encode("aeiouäöüßéá€æÆΑαΒβΓγ"))