打印组合字符串和数字

2024-03-28 13:14:55 发布

您现在位置:Python中文网/ 问答频道 /正文

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

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

Tags: and方法字符串numberis数字firstprint
3条回答

你可以这样做(可能还有其他方法):

(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)。

first,second = 10, 20

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

您还可以从Here学习字符串格式

是的。首选语法是支持str.format,而不是不推荐的%运算符。

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

相关问题 更多 >