繁体   English   中英

在python中打印包含变量的字符串

[英]printing string containing variables in python

我是python新手,尽管我知道打印包含字符串和变量的文本,但是我想问一个有关此的基本问题。 这是我的代码:

x=5                                                                                        
print ("the value of x is ",x)                                      
print "the value of x is",x

第一个打印命令打印('the value of x is ', 5) ,第二个打印命令, the value of x is 5 但是print ('hello')print 'hello'打印hello (相同),为什么呢?

因为('hello')只是'hello' ,而不是1元组。

打印是在py2x中的声明,不起作用。 因此,打印("the value of x is ",x)实际上会打印一个元组:

>>> type(('hello'))
<type 'str'>
>>> type(('hello',))  # notice the trailing `,` 
<type 'tuple'>

在py2x中,只需删除()即可获得正确的输出:

>>> print "the value of x is","foo" 
the value of x is foo

或者您也可以导入py3x的打印功能:

>>> from __future__ import print_function
>>> print ("the value of x is","foo")
the value of x is foo

假设使用Python 2.x,则print是一条语句,而逗号则使表达式成为一个元组,并用括号将其打印出来。 假设使用Python 3.x,则print是一个函数,因此第一个可以正常打印,第二个是语法错误。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM