简体   繁体   中英

print statement comma acting weird in python

When I code:

x = 4
y = 10

print("X is", x, "and Y is", y)

I get as a result:

('X is', 4, 'and Y is', 10)

Instead of:

X is 4 and Y is 10

Why is this happening? Please help.

You must be using python 2, where print is a keyword instead of a function. It is interpreting the comma-separated items inside the parentheses as a tuple, and so it is printing the tuple.

Just remove the parentheses and it will work as you expect.

Just do it the modern way with string formatting

print "x is {0} and y is {1}".format(x, y)

Or old school

print "x is " + str(x) + " and y is " + str(y)

or use

print("X is %d and Y is %d" % (x, y))

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