我们可以在位置格式化中执行算术运算吗?

时间:2018-01-23 19:06:08

标签: python python-3.x formatting

参见下面给出的程序:

# Store input numbers
num1 = input('Enter first number: ')
num2 = input('Enter second number: ')

# Add two numbers
sum = float(num1) + float(num2)

# Display the sum
print('The sum of {0} and {1} is {2}'.format(num1, num2, sum))

现在我们不能在print语句中执行sum操作吗?

我的意思是我知道我可以做到这一点

a=2
b=5
print('The sum of', a ,' and ',b,' is',(a+b))

就像我不需要以这种方式创建另一个名为变量的和。但我们可以用位置格式执行相同的操作吗?

1 个答案:

答案 0 :(得分:1)

如果您使用的是3.6或更高版本,则可以使用f-strings执行此操作:

print(f'The sum of {a} and {b} is {a+b}')
相关问题