Home The Difference in Common Usage between JavaScript and Python
Post
Cancel

The Difference in Common Usage between JavaScript and Python

Number Calculation

Retain Decimals

1
let a = 1.2345; a.toFixed(3)    //1.234
1
a = 1.2345; round(a,3);    # 1.234

String

Length

1
str.length
1
len(str)

Concatenate

1
let a = 1;    let str = `a: ${a}`;    // 'a: 1'
1
a = 1;        str = f'a: {a}';    #  'a: 1'

Slice

1
let str = '123';   str.slice(0,1);    //'1'
1
str = '123';       str[:1];    # '1'

Match and Replace

1
2
3
4
let str = 'Nice to meet you!';
str.indexOf('e');    //3
str.lastIndexOf('e');    //10
str.replace(/e/g, '1');    //'Nic1 to m11t you!'
1
2
3
str = 'Nice to meet you!'
str.find('e', beg=0, end=len(str))    # 3
str.replace('e', '1',  num=string.count(str)) # 'Nic1 to m11t you!'

JSON Serialization

1
2
3
let obj = {};
let json_str = JSON.stringify(obj);   //Serialization
let obj = JSON.parse(json_str);   //Deserialization
1
2
3
4
import json
obj = {}
json_str = json.dumps(obj, index=4)   # Serialization
obj = json.loads(json_str)   # Deserialization

Condition

if condition

1
2
3
if (1 < 2 && 3 < 4) {
  console.log('Yes.');
}
1
2
if 1 < 2 and 3 < 4:
  print('Yes.')

for loop

1
2
3
4
5
6
7
8
9
let arr = ['a', 'b', 'c'];
for (let v of arr) {     //NOTE the 'of'!
  console.log(v);	       //a b c
}									  

let _dict = {'on':'e', 'tw':'o', 'thre':'e'};
for (let k in _dict) { 
  console.log(k + _dict[k]);   //one two three
}						     
1
2
3
4
5
6
7
arr = ['a', 'b', 'c']
for v in arr:
  print(v)     # a b c

_dict = {'on':'e', 'tw':'o', 'thre':'e'}
for k, v in _dict.items():     # NEED "items()"!
  print(k + _dict[k]);         # one two three

Array

Add and Remove

1
2
3
4
let arr = [];
arr.push(1);    // Add in the tail
arr.pop();     // Remove last element
arr.length;
1
2
3
4
list = []
list.append(1)
list.pop()
len(list)

Sort

1
arr.sort((a, b) => b.score - a.score)     // descending order
1
arr.sort(key=lambda x: x.score, reverse=True)	 # descending order
This post is licensed under CC BY 4.0 by the author.

Selenium Source Code Analysis

Academic Writing I — Thinking about the Research