首页 > 解决方案 > 如何将变量存储在多行字符串变量中?

问题描述

如何将变量存储在多行字符串中?

health = 100
stats = """
Your health is: [health]
"""
print(stats)

它指示[health]的位置将替换为变量health( 100)。

标签: python

解决方案


使用f-strings - 格式化字符串的最简单实用 ( pythonic ) 方式。

health = 100

stats = f"""
Your health is: {health}
"""
print(stats)
# 
# Your health is: 100
# 

最有趣的部分是f-strings 还支持大括号内的任何 Python 表达式。

health = 100

stats = f"""
Your health is: {health * health}
"""
print(stats)
# 
# Your health is: 10000
# 

推荐阅读