Python print vs Javascript console.log()

大憨熊 提交于 2019-12-23 09:11:05

问题


In Python:

print [1,2], '\n', [3,4]

would print

[1,2]
[3,4]

In Javascript:

console.log([1,2],'\n',[3,4])

prints

[1,2] '\n' [3,4]

What is the equivalent Javascript statement to the above Python print?


回答1:


You are sending three arguments to console.log

console.log([1,2],'\n',[3,4])

Because the first argument, [1,2] doesn't contain formatting elements (e.g. %d), each argument is passed through util.inspect(). util.inspect is returning the string representation of '\n' which is not what you want. You want '\n' to be interpreted.

One solution is to concatenate all arguments into one string

> console.log([1,2]+'\n'+[3,4]);
1,2
3,4

Another is to use formatting elements as placeholders, which util.format will substitute with two array's converted values.

> console.log('%s\n%s', [1,2], [3,4]);
1,2
3,4

I assumed node.js here, but the result in Mozilla is identical.




回答2:


To be safe, just split it into multiple console.log calls.




回答3:


Use this: print ([1,2], "\'\n'", [3,4]) Here backslash denotes that \n and ' ' shouldn't perform it's operation and print as it is. Use a \ before \n and ' '



来源:https://stackoverflow.com/questions/31260437/python-print-vs-javascript-console-log

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!