简体   繁体   中英

printing string containing variables in python

I am a novice python learner, though I know printing text containing strings and variables but I want to ask a basic question regarding this. Here is my code:

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

The first print command prints ('the value of x is ', 5) while the second one prints, the value of x is 5 . But print ('hello') & print 'hello' prints hello (the same), why?

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

Print is a statement in py2x not function. so printing ("the value of x is ",x) actually prints a tuple:

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

In py2x just remove the () to get the correct output:

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

or you can also import py3x's print function:

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

Assuming Python 2.x, print is a statement and the comma makes the expression a tuple, which prints with parentheses. Assuming Python 3.x, print is a function so the first prints normally and the second is a syntax error.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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