如何在python中对整数占位符执行操作?

7wi*_*ick 5 python string python-3.x

print('%s is (%d+10) years old' % ('Joe', 42))
Run Code Online (Sandbox Code Playgroud)

输出:Joe(42 + 10)岁

预期产量:Joe今年52岁

yve*_*ine 10

您可以在Python 3.6及更高版本中使用f字符串来执行此操作。

name = "Joe"
age = 42
print(f'{name} is {age + 10} years old')
Run Code Online (Sandbox Code Playgroud)


gta*_*ico 5

字符串格式化将值插入到字符串中。要对值进行操作,您应该先计算该值,然后将其插入/格式化到字符串中。

print('%s is %d years old' % ('Joe', 42 + 10)
# or  if you really want to something like that (python 3.6+)
name = 'joe' 
age = 42
f'{name} is {age +10} years old'
Run Code Online (Sandbox Code Playgroud)