>>> print "hello world"
hello world
>>> "hello world"
'hello world'
>>>
有什么区别?
Python的Hello, World!示例主要使用:
print "hello world"
我可以去掉print
并且只使用"Hello world"
来进行Python介绍吗?
>>> print "hello world"
hello world
>>> "hello world"
'hello world'
>>>
有什么区别?
Python的Hello, World!示例主要使用:
print "hello world"
我可以去掉print
并且只使用"Hello world"
来进行Python介绍吗?
区别在于print
调用str
,而REPL(读取评估打印循环)的默认操作是对对象调用repr
,除非它是None
。
请注意,如果您不在交互式解释器中工作(不在REPL中),则在没有print
的版本中您将看不到任何输出。
还要注意输出之间的差异。 repr
会在字符串上添加引号。
>>> print "hello\nworld"
hello
world
>>> "hello\nworld"
'hello\nworld'
如果您尝试使用
"hello\nworld"
如果在程序中单独使用,当然不会得到任何输出
程序类型1
>>> print "hello world"
hello world
>>> "hello world"
'hello world'
>>> 'hello world'
'hello world'
所以在Python中,print函数将被解释为双引号和单引号相同的东西。如果没有引号或者一个不必使用双引号的句子,我只使用""。虽然,你仍然可以用\"来做到这一点。
例子 -
print 'hello\nworld' -> hello
world
print "hello\nworld" -> hello
world
并且
'hello\nworld' -> hello\nworld
print repr("hello\n\tworld\\") -> 'hello\n\tworld\\'
这取决于您的情况。
随意编辑/建议以获得更好的改进,我在此答案中可能会犯很多错误和误导。
事实上,你之所以能够执行任何操作,是因为你正在使用Python shell。 为了证明这一点,如果你实际上使用Python文件,它将什么也不会做:
Python 3.7.7 (tags/v3.7.7:d7c567b08f, Mar 10 2020, 10:41:24) [MSC v.1900 64 bit (AMD64)] on win32
Type "help", "copyright", "credits" or "license()" for more information.
>>>
==== RESTART: C:/Users/s-wan/AppData/Local/Programs/Python/Python37/testhelloworld.py ===
>>>
但是如果你在shell中实际使用它,那么它会用单引号打印出来:
>>> "Hello World"
'Hello World'
使用
print('hello world')
将会打印出不带引号的“hello world”。Shell 和实际文件可能会产生不同的结果。
如果你在命令行上,你可以避免使用print函数。否则,你必须使用print函数。