打印组合字符串和数字 [英] Print Combining Strings and Numbers

查看:52
本文介绍了打印组合字符串和数字的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

要在 Python 中打印字符串和数字,除了执行以下操作还有其他方法吗:

To print strings and numbers in Python, is there any other way than doing something like:

first = 10
second = 20
print "First number is %(first)d and second number is %(second)d" % {"first": first, "second":second}

推荐答案

使用不带括号的打印函数适用于旧版本的 Python,但 Python3 不再支持,因此您必须将参数放在括号内.但是,有解决方法,如该问题的答案中所述.由于对 Python2 的支持已于 2020 年 1 月 1 日结束,因此答案已修改为与 Python3 兼容.

Using print function without parentheses works with older versions of Python but is no longer supported on Python3, so you have to put the arguments inside parentheses. However, there are workarounds, as mentioned in the answers to this question. Since the support for Python2 has ended in Jan 1st 2020, the answer has been modified to be compatible with Python3.

您可以执行以下任何操作(可能还有其他方法):

You could do any of these (and there may be other ways):

(1)  print("First number is {} and second number is {}".format(first, second))
(1b) print("First number is {first} and number is {second}".format(first=first, second=second)) 

(2) print('First number is', first, 'second number is', second) 

(注意:逗号分隔后会自动加一个空格)

(3) print('First number %d and second number is %d' % (first, second))

(4) print('First number is ' + str(first) + ' second number is' + str(second))
  

使用format() (1/1b) 是首选.

Using format() (1/1b) is preferred where available.

这篇关于打印组合字符串和数字的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆