Say we want to concatenate elements within a JavaScript array (or Python list). i.e.
- Input: an array that looks like this
['hello', 'world', '123', '!!!']
- Process: concatenate the string elements within the array
- Output:
hello world 123 !!!
This post shows the similarity (and difference) of the JavaScript and Python syntax. (in case you start using JavaScript but from a Python background. Or vice versa, start using Python but from a JavaScript background)
Pay attention to Step 3 - compare this to the Python version.
// (Step 1) define an array
const words = ['hello', 'world', '123', '!!!']
// (Step 2) define a string delimiter
const delimiter = ' '
// (Step 3) concatetenate elements in the array and form a long string
const sentence = words.join(delimiter)
// (Step 4) print it to terminal
console.log(sentence)
// -> hello world 123 !!!
Pay attention to Step 3 - compare this to the JavaScript version.
# (Step 1) define a list
words = ['hello', 'world', '123', '!!!']
# (Step 2) define a string delimiter
delimiter = ' '
# (Step 3) concatetenate elements in the array and form a long string
sentence = delimiter.join(words)
# (Step 4) print it to terminal
print(sentence)
# -> hello world 123 !!!
Note the slight difference in syntax in Step 3. (Let's called a JavaScript array a "list" for now, for ease of visualizing the difference in syntax)
- In JavaScript, we do:
list.join(string)
- In Python, we do:
string.join(list)
See that "flip" in syntax (in the order of list and string)?