python打印语句中逗号和加号有什么区别?

时间:2019-02-13 06:16:33

标签: python python-3.x

我希望了解print((x,y)*5)的输出。我想知道幕后到底发生了什么。 (对我来说,好像变成了清单。对吗?)

x = 'Thank'
y = 'You'

print(x+y)
print(x,y)

print((x+y)*5) 
print((x,y)*5) #This one..

我是Python的初学者,这是我第一次问一个问题。如果这个问题看起来很幼稚,请原谅我。我尝试了谷歌搜索,但没有帮助。

2 个答案:

答案 0 :(得分:3)

x = 'Thank'
y = 'You'


# concatenation of string x and y which is treated as a single element and then 
# printed (Here, only a single argument is passed to the print function).
print(x+y)  
# Output: ThankYou  (Simple String concatenation)


# Here, two different arguments are passed to the print function.
print(x,y)  
# Output python 2: ('Thank', 'You')  (x and y are treated as tuple
# Output python 3: Thank You  (x and y are comma seperated and hence, 
# considered two different elements - the default 'sep=" "' is applied.)


# The concatenated result of (x + y) is printed 5 times.
print((x+y)*5) 
# Output: ThankYouThankYouThankYouThankYouThankYou  

# x and y are made elements of a tuple and the tuple is printed 5 times.
print((x,y)*5) 
# Output: ('Thank', 'You', 'Thank', 'You', 'Thank', 'You', 'Thank', 'You', 'Thank', 'You')  

答案 1 :(得分:-1)

如果操作数是字符串,

plus充当串联运算符,否则充当数学加号运算符。print函数中的逗号用于分隔变量:string的情况下,print中的+和+的作用相同,但本质上是不同的: +从操作数创建新对象,而逗号使用对象,但未创建新对象:

print('Delhi'+'is capital')

print(2+6)

var1='Hello'
var2='!!'
print(var1,var2)
print(2,6)