Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to escape UNICODE string in python (to javascript escape)

I have the following string "◣⛭◣◃✺▲♢" and I want to make that string into "\u25E3\u26ED\u25E3\u25C3\u273A\u25B2\u2662". Exactly the same as this site does https://mothereff.in/js-escapes

I was wondering if this is possible in python. I have tried allot of stuff from the unicode docs for python but failed miserably.

Example of what I tried before:

#!/usr/bin/env python
# -*- coding: latin-1 -*-

f = open('js.js', 'r').read()

print(ord(f[:1]))

help would be appreciated!

like image 667
J. Dough Avatar asked Sep 20 '25 02:09

J. Dough


1 Answers

Considering you're using Python 3:

unicode_string="◣⛭◣◃✺▲♢"
byte_string= unicode_string.encode('ascii', 'backslashreplace')
print(byte_string)

See codecs module documentation for more infotmation.

However, to work with JavaScript notation, there's a special module json, and then you could achieve the same thing:

import json
unicode_string="◣⛭◣◃✺▲♢"
json_string=json.dumps(unicode_string)
print(json_string)
like image 187
Nikita Avatar answered Sep 22 '25 17:09

Nikita