20 06 2012
Javascript to Python API reference guide
Do you also keep searching for JS terms to find out what Python API to use? I use this article as a reference guide of the javascript to python API.
Prologue
After constantly working with javascript for more than seven years I’ve decided to explore another programming language. Python became my language of choice.
Since I’m not doing python coding fulltime, I keep diving into the same docs of python again and again, in order to recall how to do simple and basic stuff. For example: looping through the different data types or searching in a string for a pattern.
My long-running relationship with JavaScript only makes the process of learning even more difficult. Every time I’m trying to do something in python i’m searching for the equivalent of javascript API in python. However it can take a long time before the answer is found. For example, how would you do charCodeAt
in python? I have to say it took me a while to find an answer to this question, but then, time passes by and I forget it again.
For this reason I wrote this short reference guide. Though it only contains stuff which differs from the javascript perspective. This means I haven’t done a mapping for methods which are the same in both languages.
One piece of advice. In the python REPL you can execute the help
function and pass any object to it. The help
function will show you documentation regarding the passed object e.g.,
help([])
will return documentation about arrays.
Global stuff
escape
Syntax: escape(x)
import urllib;
urllib.quote(x)
unescape
Syntax: unescape(x)
import urllib
urllib.unquote(x)
parseFloat
Syntax: parseFloat(x)
float(x)
parseInt
Syntax: parseInt(x)
int(x)
Note: Be carefull with this one, since it might other thing than you expect. Often parseInt is used to parse any string ( with int or float in it) to an integer. In case you try to parse a float or non-valid number it will throw an error. This means that, stuff like:
int("123.456")
will break in python, but is still valid in javascript.
String
charAt
Syntax: “string”.charAt(index)
"string"[index]
charCadeAt
Syntax: “string”.charCodeAt(index)
ord("string"[index])
indexOf
Syntax: “string”.indexOf(“searchValue”,[fromIndex])
"string".find("searchValue", [fromIndex])
fromCharCode
Syntax: String.fromCharCode(charCode)
chr(charCode)
lastIndexOf
Syntax: “string”.lastIndexOf(“searchValue”,[fromIndex])
"string".rfind("searchValue", [fromIndex])
match
Placed inside RegExp object
replace
Placed inside RegExp object
slice
Syntax: “string”.slice(startIndex)
"string"[startIndex:]
Syntax: “string”.slice(startIndex, endIndex)
"string"[startIndex:endIndex]
split
Syntax: “string”.split(delimiter)
"str".split(delimiter)
substr
Syntax: “string”.substr(start)
"string"[start:]
Syntax: “string”.substr(start, [length])
"string"[start:start+length]
Note: In javascript substring expects length and in Python an endIndex. The comparable function in javascript is slice
substring
Syntax: “string”.substring(start, end)
"string"[start:end]
toLowerCase
Syntax: “string”.toLowerCase()
"string".lower()
toUpperCase
Syntax: “string”.toUpperCase()
"string".upper()
RegExp
- http://docs.python.org/release/2.5.2/lib/match-objects.html
- http://docs.python.org/dev/howto/regex.html
- http://docs.python.org/library/re.html
- http://www.tutorialspoint.com/python/python_reg_expressions.htm
RegExp support in python is pretty BIG and is much more extended than in javascript ( IMHO: mostly like anything in Python ). That’s why I have dedicated a separate article to this subject. So if you are going to use regexps intensively I recommend you read that article as well.
Also match
and replace
are part of the String object, I specify it here in order to emphasize that searching and replacing in Python is not the same as it is in JavaScript.
test
Syntax: var r = /regexp/.test(“string”)
import re
r = (re.search(r"regexp", "someString") != None)
Note: search doesn’t return boolean value, but None if no match is found.
replace
Syntax: “string”.replace(/regexp/, “newSubStr”)
import re
re.sub(r"regepx", "originalString", "newSubStr")
*Syntax: “string”.replace(/regexp/, function(str, p1…p2, offset, s){})
import re
match
Syntax: “string”.match(/regexp/g)
import re
re.findall(r"regexp", "import”)
Note: Please note that only match
with the GLOBAL flag is presented here. The reason for that is explained in “Introduction into Python Regexp” as a follow up article.
Date
One of the difference between Python and JavaScript is that Python works with seconds while JavaScript with milliseconds.
Getting Date object of now
Syntax: var now = new Date()
import datetime
now = datetime.datetime.now()
Creating date object based on year, month, etc
Syntax: var d = new Date(year, month, date)
import datetime
datetime.datetime(year, month+1, date)
Note: The month in python is from 1<=12 and not from 0 like in javascript
Creating date object based on epoch
Syntax: var d = new Date(epoch)
import datetime
datetime.fromtimestamp(epoch)
getDate
Syntax: dateObject.getDate( )
dateObject.day
getDay
Syntax: d.getDay()
d.weekday()
getFullYear
Syntax: d.getFullYear()
d.year
getMonth
Syntax: d.getMonth()
(d.month - 1)
Note: That month in python is from 1<=12 and not from 0 like in JavaScript
getHours
Syntax: d.getHours()
d.hour
getMilliseconds
Syntax: d.getMilliseconds()
(d.microsecond * 0.001)
getMinutes
Syntax: d.getMinutes()
d.minute
getSeconds
Syntax: d.getSeconds()
d.second
getTime
Syntax: d.getTime()
import time
time.mktime(d.timetuple())
Math
random
Syntax: Math.random()
import random
random.random()
round
Syntax: Math.round(number)
int(round(number))
Note: round in Python always returns a floating number, while in JavaScript an integer and keep that in mind.
abs, ceil, floor
# All the other methods of math are mostly equiualent to Math in javascript
import math
math.abs()
math.fabs(x)
math.ceil(x)
math.floor(x)
Array
push
Syntax: arr.push(item)
arr.append(item)
Note: Python has a different return value, so if you need the length of the array wrap it in a len
function
len(arr.append(item))
shift
Syntax: arr.shift(item)
arr.insert(0, item)
unshift
Syntax: arr.unshift()
arr.pop(0) # different return
length
Syntax: arr.length
len(one)
slice
Syntax: arr.slice(begin)
arr[begin:]
*Syntax: arr.slice(begin, end)
arr[begin:end]
concat
Syntax: arr.concat(secondArray)
arr + secondArray
Note: concat is making a shallow copy of an array
When doing a new copy of an array in javascript you do this:
[].concat(x)
But in python you can use this syntax:
x[:]
join
Syntax: arr.join(delimiter)
delimiter.join(arr)
Note: As you can see, the method for joining an array is sitting inside the string class and not in the array class as in javascript
JavaScript function declaration among the browsers Introduction into regular expressions in Python ( for Javascripters )
Are there any automatic js to python compilers?
Amazing post, just what I was looking for, thanks! 🙂
Thank you very much !!!