Python打印变量后打印文本

5 投票
3 回答
101069 浏览
提问于 2025-04-17 13:11

我想在打印我的变量之后再打印一些文字,像这样:

print('Blablabla' var ' blablabla')

现在的效果是这样的:

 print('The enemey gets hit for %d' % damage)

我想在打印完伤害变量后,显示“Hitpoints”这个词。

3 个回答

1

只需要在你的字符串中加上 hitpoints 就可以了:

print('the enemy gets mutilated for %d hitpoints!' % damage)
5

这样看起来好多了。;0)

damage = 10
print(f'The enemey gets hit for {damage} hitpoints')

(适用于 Python 3.6 及以上版本)

25

只需要把生命值加上:

print('The enemey gets hit for %d hitpoints' % damage)

格式化操作符 % 非常强大,可以看看 所有的占位符选项。不过,它计划逐渐被 str.format 取代:

print('The enemey gets hit for {} hitpoints'.format(damage))

另外,你也可以把 damage 的值转换成字符串,然后用 + 来连接字符串:

print('The enemy gets hit for ' + str(damage) + ' hitpoints')

撰写回答