python - python 中 print ('text' +str(variable)) 和 print ('stuff' , variable) 有什么区别?

标签 python

在Python中编写打印语句时,最好的做法是这样写

print('some text', variable, variable, expression)

print('some text' + str(variable) ...)

打印如何以不同的方式处理这些?

最佳答案

你的主要区别是,如果你要“参数化”打印函数(正如 Vikram Eloquent 地说的那样),print 有一个默认的 sep 参数,它将你的参数与无论 sep 是什么(默认为 ' ')。如果不将变量拆分为参数并将它们连接成一个字符串,则不会有空格。 即:

>>> print(1,2)
1 2
>>> print(str(1)+str(2))
12

我认为您想知道的另一件事是 str 的调用。简而言之,print 无论如何都会对您的参数调用 str(parameter),在这方面,确实没有区别。

总而言之,print 输出的字符串几乎与以下内容相同:

sep.join(parameters) #where sep is defaulted to ' '

关于python - python 中 print ('text' +str(variable)) 和 print ('stuff' , variable) 有什么区别?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33683149/

相关文章:

Python OpenCV 与 CascadeClassifier 发生错误

python - Ubuntu 升级后干净卸载 Python 软件包

python - Jupyter iPython Notebook 和命令行产生不同的结果

python - 安装 Zope 2 最简单的 buildout.cfg 是什么?

python - Tensorflow prefetch_to_device

python - 已安装 Scrapy,但无法在命令行中识别

python - Tkinter:点击时移动到随机位置

python - 尝试使用 Python 3.7.2 和 IMAPClient 批量删除电子邮件 - imaplib.IMAP4.error : UID command error: BAD [b'Command line too large']

python - 有没有办法可以处理 Langchain QA 检索中的上下文和一般问题?

python - 从一行python加载x个数字