打印组合字符串和数字

dar*_*sky 59 python python-2.7

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

first = 10
second = 20
print "First number is %(first)d and second number is %(second)d" % {"first": first, "second":second}
Run Code Online (Sandbox Code Playgroud)

Lev*_*von 101

你可以做任何这些(也可能有其他方法):

(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) 
Run Code Online (Sandbox Code Playgroud)

要么

(2) print 'First number is', first, ' second number is', second
Run Code Online (Sandbox Code Playgroud)

要么

(3) print 'First number %d and second number is %d' % (first, second)
Run Code Online (Sandbox Code Playgroud)

要么

(4) print 'First number is' + str(first) + 'second number is' + str(second)
Run Code Online (Sandbox Code Playgroud)

在可用的情况下,首选使用format()(1/1b).


小智 9

如果你使用的是 3.6 试试这个

 k = 250
 print(f"User pressed the: {k}")
Run Code Online (Sandbox Code Playgroud)

输出:用户按下:250


Ant*_*ony 7

就在这里.首选语法是支持str.format已弃用的%运算符.

print "First number is {} and second number is {}".format(first, second)
Run Code Online (Sandbox Code Playgroud)


Mat*_*lia 6

其他答案解释了如何生成像示例中那样格式化的字符串,但如果您需要做的就是print这些内容,您可以简单地编写:

first = 10
second = 20
print "First number is", first, "and second number is", second
Run Code Online (Sandbox Code Playgroud)