a = 10
b = 20
c = a + b
#Normal string concatenation
print("sum of", a , "and" , b , "is" , c)
#convert variable into str
print("sum of " + str(a) + " and " + str(b) + " is " + str(c))
# if you want to print in tuple way
print("Sum of %s and %s is %s: " %(a,b,c))
#New style string formatting
print("sum of {} and {} is {}".format(a,b,c))
#in case you want to use repr()
print("sum of " + repr(a) + " and " + repr(b) + " is " + repr(c))
EDIT :
#New f-string formatting from Python 3.6:
print(f'Sum of {a} and {b} is {c}')
有很多方法可以做到这一点。要使用
%
格式修复当前代码,需要传入一个元组:以元组形式传递:
只有一个元素的元组看起来像
('this',)
。以下是其他一些常见的方法:
作为字典传递:
还有新样式的字符串格式,可能更容易阅读:
使用新样式的字符串格式:
对数字使用新样式的字符串格式(用于重新排序或多次打印同一个字符串):
对显式名称使用新样式的字符串格式:
连接字符串:
最清楚的两个,在我看来:
只需将值作为参数传递:
如果不希望在上面的示例中由
print
自动插入空格,请更改sep
参数:如果您使用的是Python2,将无法使用最后两个,因为
print
不是Python2中的函数。但是,您可以从__future__
导入此行为:在Python 3.6中使用新的
f
字符串格式:有很多方法可以打印出来。
让我们看一看另一个例子。
使用:
.format()
:或:
或:
或:
相关问题 更多 >
编程相关推荐