打印组合字符串和数字

时间:2012-08-18 13:32:47

标签: 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}

9 个答案:

答案 0 :(得分:93)

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

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

答案 1 :(得分:7)

是的。首选语法是支持str.format而不是已弃用的%运算符。

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

答案 2 :(得分:4)

first,second = 10, 20

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

您还可以从Here

学习字符串格式

答案 3 :(得分:3)

其他答案解释了如何生成一个像您的示例中那样格式化的字符串,但如果您需要做的只是print那些东西,您可以简单地写一下:

first = 10
second = 20
print "First number is", first, "and second number is", second

答案 4 :(得分:1)

如果你使用3.6试试这个

 k = 250
 print(f"User pressed the: {k}")
  

输出:用户按下:250

答案 5 :(得分:1)

当我开始学习python时,我和Java编码员陷入了同样的困境,我们通常使用+运算符向字符串添加数字。我开始学习数学表达式已经两天了。根据我的发现,

first = 10;
second = 20;
print "First Number is" , first, "Second number is" , second

这很好,也

print  first, "is the First Number" , second, "is the Second number"

也可以。

答案 6 :(得分:1)

在Python 3.6中

a, b=1, 2 

print ("Value of variable a is: ", a, "and Value of variable b is :", b)

print(f"Value of a is: {a}")

答案 7 :(得分:0)

%i或%d均可用于整数打印。我正在使用python 3 +

-例如,

a=100
b=20
c= "is"
print("a %s = %d,b %s =%i" %(c,a,c,b))

-输出为:

a是= 100,b是= 20

答案 8 :(得分:-1)

Python 3: some_var = 24.37 print(“ Hello”,123,“ \ n您如何” +“ Bro”,“?” +“ \ n”,“ \ n我是2好” +“ \ n \ n”,some_var) 您可以使用大多数数据类型。

相关问题