I’m a beginner to Python trying to decode this javascript sequence. I’m not only a beginner in Python, I understand javascript even less 🙂 I know i could put it into an online decoder such as this: http://coderstoolbox.net/string/ but I want to deal with it myself – more for practice than anything else… Im using Beautiful Soup to get the data, so I have its functions available for decoding.
If anyone can point me to equivalent functions in python I would appreciate it.
function encode(str){
var t=''; var s=unescape(str);
var x=Math.round(Math.sqrt(49));
for(var i=0;i<s.length;i++) t+=
String.fromCharCode(s.charCodeAt(i)^(i%2?x:0));
print(t);
}
This is my understanding of it so far:
- i think I can use ‘HTML entities in BS to unescape..?
- the second one just seems to be a constant number ? square root of 49 rounded…
- sets up the loop
- this is the one i dont get. 1 i dont know what the fromCharCode function does. 2 not sure what the bit at the end is. looks like its getting a character code from i to the power something. i understand i is being modulo’d with 2 but what is the ‘?x:0’ bit ? – how would you replicate this in Python ?
thanks for reading !
EDIT: is there a python library that can just run this code ? I’ve done this before with bash and used rhino, but the alternatives in Python seem a bit scary for a beginner, eg spidermonkey, etc…
1) the python equivalent to unescape is urllib.unquote() in python 2.x series and urllib.parse.unquote() in python 3.x series
2) you guess the simplest way to do it is to do
x = 73) the simplest way to loop on string charters is to do
for c in string:but to have the index you should dofor i,c in enumerate(string):4) the string.charChodeAt(c) is the same than chr(c)
finally I would duplicate the loop part as follow:
in fact using a temporary array to make the appends is more efficient than happening to strings as the strings don’t mutate