Python中print语句中逗号和加号的区别是什么?

6

我想了解print((x,y)*5)的输出。我希望知道背后实际发生了什么。(对我来说,它似乎变成了一个列表。我是不是正确的?)

我希望理解print((x,y)*5)的输出结果。实际上,这个表达式会将元组(x,y)重复5次,并将结果作为一个新的元组返回。所以你是正确的,结果看起来像一个列表。

x = 'Thank'
y = 'You'

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

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

我是Python的初学者,这是我第一次提问。如果我的问题显得幼稚,请原谅。我已经尝试过谷歌搜索,但没有找到答案。


加号连接符用于连接字符串,而另一个则仅显示变量的值。 - Yash Kumar Atri
试着用整数或浮点数,你就会明白了。 - Yash Kumar Atri
x+y 进行连接并打印 5 次,其中 xy 是两个不同的值,并交替乘以 5 次,以列表形式显示。因此,它是像这样的:首先是 x,然后是第二个位置上的 y,重复 5 次。 - Yash Kumar Atri
print("ab" + "ra" + "ca" + "da" + "bra")print("ab","ra","ca","da","bra")print("ab","ra","ca","da","bra", sep = "WUSH") - 使用 sep 分隔的实体将被打印,而连接的字符串将作为一个连接的字符串打印。打印元组(而不是列表)应该很明显。 - Patrick Artner
Python中使用逗号、连接和字符串格式化的区别 - Josh Correia
2个回答

8
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')  

2
值得解释一下打印的内容以及原因。你已经完成了一半。 - Mark Ransom
距离停止使用Python 2.x不到10个月了:https://pythonclock.org/ - 你的回答是针对Python 2的,问题是关于Python 3的,我已经进行了编辑。您可以使用例如http://www.pyfiddle.io(切换到3.x)进行验证。 - Patrick Artner
@PatrickArtner,感谢您的编辑! - taurus05
非常感谢您解决我的疑问!现在我完全明白了。 - Vijay Sharma
愉快学习! - taurus05

0

如果操作数是字符串,则加号充当连接运算符,否则它充当数学加法运算符。而在print函数中,逗号用于分隔变量:对于字符串,print中的+和逗号作用相同,但从根本上讲它们是不同的:+从操作数创建新对象,而逗号使用对象并不创建新对象:

print('Delhi'+'is capital')

print(2+6)

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

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接