我知道有 4 种方法可以在 python (Python 3) 上实现这一点:
1) 串联:
您可以使用+ 来连接两个字符串,但是您只能连接字符串类型的数据,这意味着需要使用str() 函数将非字符串类型的数据转换为字符串。例如:
print("The Enemy's health is " + str(EnemyHealth) + ". The Enemy is " + EnemyIs + ".")
# output = "The Enemy's health is 0. The Enemy is dead."
2) 利用 Python 3 的 print() 函数,该函数可以接受多个参数参数:
这里你的print() 语句类似于上面的连接语句,除非我使用+ 连接你需要用, 替换它。使用它的好处是,不同的数据类型将自动转换为字符串,即不再需要str() 函数。例如:
print("The Enemy's health is ", EnemyHealth, ". The Enemy is ", EnemyIs, ".")
# output = "The Enemy's health is 0. The Enemy is dead."
3) 使用字符串替换方法
您的代码不起作用的原因是因为%d 意味着您将用整数替换它,因此要使您的代码正常工作,因为存储在变量EnemyIs 上的字符串需要替换为%s用于声明它将被替换为字符串。因此,要解决您的问题,您需要这样做:
print("The Enemy's health is %d. The Enemy is %s." % (EnemyHealth, EnemyIs))
# output = "The Enemy's health is 0. The Enemy is dead."
4)python字符串的format()方法(这是最好的使用方法)
这是python中所有字符串的内置方法,它允许您轻松地将python字符串中的占位符{}替换为任何变量。与上面的解决方案 3 不同,此 format() 方法不需要您将不同的数据类型表示或转换为字符串,因为它会自动为您执行此操作。例如,要使您的打印语句起作用,您可以这样做:
print("The Enemy's health is {}. The Enemy is {}.".format(EnemyHealth, EnemyIs))
或
print("The Enemy's health is {0}. The Enemy is {1}.".format(EnemyHealth, EnemyIs))
# output = "The Enemy's health is 0. The Enemy is dead."
更新:
5) F-Strings
从 python 3.6+ 开始,您现在还可以使用 f 字符串来替换字符串中的变量。该方法类似于上述.format() 方法,在我看来是对str.format() 方法的更好升级。要使用此方法,您只需在定义字符串时在开场引号之前声明f,然后在字符串中使用格式{[variable name goes here]} 即可。例如,要使您的打印语句起作用,使用此方法,您可以:
print(f"The Enemy's health is {EnemyHealth}. The Enemy is {EnemyIs}.")
# output = "The Enemy's health is 0. The Enemy is dead."
正如您使用此方法所见,variable name 直接在大括号 {} 内实例化。